Id
stringlengths
1
5
Tags
stringlengths
3
75
Title
stringlengths
15
150
CreationDate
stringlengths
23
23
Body
stringlengths
51
27.6k
Answer
stringlengths
42
31k
90285
|led|stepper-motor|
Blink LED without delay with stepper motor
2022-07-25T06:35:47.487
<p>Based on a <a href="https://arduino.stackexchange.com/questions/90281/stepper-motor-and-blink-led">previous question</a> I modified the script to use blink without delay.</p> <p>Unfortunately, it does not work, any idea why?</p> <p>I am using SparkFun RedBoard Plus, Qwiic LED Stick - APA102C, Adafruit Stepper motor - NEMA-17 size - 200 steps/rev and Adafruit Motor Shield V2.</p> <p>Modified code (based on @Michel Keijzers, see below):</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_MotorShield.h&gt; #include &quot;Qwiic_LED_Stick.h&quot; // Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_LED_Stick // Variables will change: int ledState = LOW; // ledState used to set the LED unsigned long previousMillis = 0; // will store last time LED was updated // constants won't change: const long interval = 500; // interval at which to blink (milliseconds) LED LEDStick; //Create an object of the LED class Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2); void setup() { Wire.begin(); Serial.begin(115200); while (!Serial); Serial.println(&quot;Stepper test!&quot;); if (!AFMS.begin()) { // if (!AFMS.begin(1000)) { Serial.println(&quot;Could not find Motor Shield. Check wiring.&quot;); while (1); } Serial.println(&quot;Motor Shield found.&quot;); myMotor-&gt;setSpeed(50); // 50 rpm //Start up communication with the LED Stick if (!LEDStick.begin()) { Serial.println(&quot;Qwiic LED Stick failed to begin. Please check wiring and try again!&quot;); while (1); } Serial.println(&quot;Qwiic LED Stick ready!&quot;); // LEDStick.setLEDColor(255, 0, 0); LEDStick.setLEDBrightness(1); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis &gt;= interval) { // save the last time you blinked the LED previousMillis = currentMillis; ledState = !ledState; // set the LED with the ledState of the variable: uint8_t intensity = ledState == HIGH ? 255 : 0; LEDStick.setLEDColor(intensity, intensity, intensity); } Serial.println(&quot;Single coil steps&quot;); myMotor-&gt;step(200, FORWARD, SINGLE); } </code></pre> <p>Code:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_MotorShield.h&gt; #include &quot;Qwiic_LED_Stick.h&quot; // Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_LED_Stick // Variables will change: int ledState = LOW; // ledState used to set the LED unsigned long previousMillis = 0; // will store last time LED was updated // constants won't change: const long interval = 1000; // interval at which to blink (milliseconds) LED LEDStick; //Create an object of the LED class Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2); void setup() { Wire.begin(); Serial.begin(115200); while (!Serial); Serial.println(&quot;Stepper test!&quot;); if (!AFMS.begin()) { // if (!AFMS.begin(1000)) { Serial.println(&quot;Could not find Motor Shield. Check wiring.&quot;); while (1); } Serial.println(&quot;Motor Shield found.&quot;); myMotor-&gt;setSpeed(50); // 50 rpm //Start up communication with the LED Stick if (LEDStick.begin() == false) { Serial.println(&quot;Qwiic LED Stick failed to begin. Please check wiring and try again!&quot;); while (1); } Serial.println(&quot;Qwiic LED Stick ready!&quot;); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis &gt;= interval) { // save the last time you blinked the LED previousMillis = currentMillis; // if the LED is off turn it on and vice-versa: if (ledState == LOW) { ledState = HIGH; } else { ledState = LOW; } // set the LED with the ledState of the variable: LEDStick.setLEDColor(50, 50, 50); } Serial.println(&quot;Single coil steps&quot;); myMotor-&gt;step(200, FORWARD, SINGLE); } </code></pre>
<p>You only set (assign) <code>ledState</code>, but you never use it.</p> <p>I think the following fragment</p> <pre><code>// set the LED with the ledState of the variable: LEDStick.setLEDColor(50, 50, 50); </code></pre> <p>Should be something like:</p> <pre><code>// set the LED with the ledState of the variable: uint8_t intensity = ledState == HIGH ? 255 : 0; LEDStick.setLEDColor(intensity, intensity, intensity); </code></pre> <p>This 'converts' the ledState into white (RGB values 255) when HIGH or black/off (RGB values 0) when LOW.</p> <p>Also you can change the line</p> <pre><code>if (LEDStick.begin() == false) { </code></pre> <p>into</p> <pre><code>if (!LEDStick.begin()) { </code></pre> <p>and change the lines</p> <pre><code>// if the LED is off turn it on and vice-versa: if (ledState == LOW) { ledState = HIGH; } else { ledState = LOW; } </code></pre> <p>into</p> <pre><code>// if the LED is off turn it on and vice-versa: ledState = ledState == LOW ? HIGH : LOW; </code></pre> <p>or even</p> <pre><code>ledState = !ledState; </code></pre>
90298
|esp8266|compile|
"previous declaration of 'HTTPMethod HTTP_HEAD'"
2022-07-26T06:18:20.380
<p>I'm getting the following error when I try to compile my code on my LOLIN(WeMos) D1 R1:</p> <pre><code>In file included from C:\Users\Administrator\Documents\Arduino\libraries\WiFiManager/WiFiManager.h:17, from C:\Users\Administrator\Desktop\from\from.ino:6: C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:19: error: 'HTTP_ANY' conflicts with a previous declaration 47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS }; | ^~~~~~~~ In file included from C:\Users\Administrator\Desktop\from\from.ino:5: C:\Users\Administrator\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:69:3: note: previous declaration 'WebRequestMethod HTTP_ANY' 69 | HTTP_ANY = 0b01111111, | ^~~~~~~~ In file included from C:\Users\Administrator\Documents\Arduino\libraries\WiFiManager/WiFiManager.h:17, from C:\Users\Administrator\Desktop\from\from.ino:6: C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:29: error: 'HTTP_GET' conflicts with a previous declaration 47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS }; | ^~~~~~~~ In file included from C:\Users\Administrator\Desktop\from\from.ino:5: C:\Users\Administrator\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:62:3: note: previous declaration 'WebRequestMethod HTTP_GET' 62 | HTTP_GET = 0b00000001, | ^~~~~~~~ In file included from C:\Users\Administrator\Documents\Arduino\libraries\WiFiManager/WiFiManager.h:17, from C:\Users\Administrator\Desktop\from\from.ino:6: C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:39: error: 'HTTP_HEAD' conflicts with a previous declaration 47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS }; | ^~~~~~~~~ In file included from C:\Users\Administrator\Desktop\from\from.ino:5: C:\Users\Administrator\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:67:3: note: previous declaration 'WebRequestMethod HTTP_HEAD' 67 | HTTP_HEAD = 0b00100000, | ^~~~~~~~~ In file included from C:\Users\Administrator\Documents\Arduino\libraries\WiFiManager/WiFiManager.h:17, from C:\Users\Administrator\Desktop\from\from.ino:6: C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:50: error: 'HTTP_POST' conflicts with a previous declaration 47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS }; | ^~~~~~~~~ In file included from C:\Users\Administrator\Desktop\from\from.ino:5: C:\Users\Administrator\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:63:3: note: previous declaration 'WebRequestMethod HTTP_POST' 63 | HTTP_POST = 0b00000010, | ^~~~~~~~~ In file included from C:\Users\Administrator\Documents\Arduino\libraries\WiFiManager/WiFiManager.h:17, from C:\Users\Administrator\Desktop\from\from.ino:6: C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:61: error: 'HTTP_PUT' conflicts with a previous declaration 47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS }; | ^~~~~~~~ In file included from C:\Users\Administrator\Desktop\from\from.ino:5: C:\Users\Administrator\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:65:3: note: previous declaration 'WebRequestMethod HTTP_PUT' 65 | HTTP_PUT = 0b00001000, | ^~~~~~~~ In file included from C:\Users\Administrator\Documents\Arduino\libraries\WiFiManager/WiFiManager.h:17, from C:\Users\Administrator\Desktop\from\from.ino:6: C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:71: error: 'HTTP_PATCH' conflicts with a previous declaration 47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS }; | ^~~~~~~~~~ In file included from C:\Users\Administrator\Desktop\from\from.ino:5: C:\Users\Administrator\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:66:3: note: previous declaration 'WebRequestMethod HTTP_PATCH' 66 | HTTP_PATCH = 0b00010000, | ^~~~~~~~~~ In file included from C:\Users\Administrator\Documents\Arduino\libraries\WiFiManager/WiFiManager.h:17, from C:\Users\Administrator\Desktop\from\from.ino:6: C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:83: error: 'HTTP_DELETE' conflicts with a previous declaration 47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS }; | ^~~~~~~~~~~ In file included from C:\Users\Administrator\Desktop\from\from.ino:5: C:\Users\Administrator\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:64:3: note: previous declaration 'WebRequestMethod HTTP_DELETE' 64 | HTTP_DELETE = 0b00000100, | ^~~~~~~~~~~ In file included from C:\Users\Administrator\Documents\Arduino\libraries\WiFiManager/WiFiManager.h:17, from C:\Users\Administrator\Desktop\from\from.ino:6: C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:96: error: 'HTTP_OPTIONS' conflicts with a previous declaration 47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS }; | ^~~~~~~~~~~~ In file included from C:\Users\Administrator\Desktop\from\from.ino:5: C:\Users\Administrator\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:68:3: note: previous declaration 'WebRequestMethod HTTP_OPTIONS' 68 | HTTP_OPTIONS = 0b01000000, | ^~~~~~~~~~~~ exit status 1 Error compiling for board LOLIN(WeMos) D1 R1. </code></pre> <p>Here is my code:</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;ESP8266WiFi.h&gt; #include &lt;ESPAsyncTCP.h&gt; #include &lt;ESPAsyncWebServer.h&gt; #include &lt;WiFiManager.h&gt; AsyncWebServer server(80); const char* PARAM_INPUT_1 = &quot;input1&quot;; const char* PARAM_INPUT_2 = &quot;input2&quot;; const char* PARAM_INPUT_3 = &quot;input3&quot;; const char index_html[] PROGMEM = R&quot;rawliteral( &lt;!DOCTYPE HTML&gt;&lt;html&gt;&lt;head&gt; &lt;title&gt;ESP Input Form&lt;/title&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;style&gt;html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;} .button { background-color: #195B6A; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;} .button2 {background-color: #195B6A;}&lt;/style&gt; &lt;/head&gt;&lt;body&gt; &lt;form action=&quot;/get&quot;&gt; input1: &lt;input type=&quot;text&quot; name=&quot;input1&quot; style=&quot;background-color: #195B6A; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;&quot;&gt; &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt; &lt;/form&gt;&lt;br&gt; &lt;form action=&quot;/get&quot;&gt; input2: &lt;input type=&quot;text&quot; name=&quot;input2&quot;&gt; &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt; &lt;/form&gt;&lt;br&gt; &lt;form action=&quot;/get&quot;&gt; input3: &lt;input type=&quot;text&quot; name=&quot;input3&quot;&gt; &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt; &lt;/form&gt; &lt;h1&gt;SmartHomeHarris-CoLTD&lt;/h1&gt; &lt;p&gt;GPIO 1 - State off&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;/1/on&quot;&gt;&lt;button class=&quot;button&quot;&gt;ON&lt;/button&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;GPIO 2 - State off&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;/2/on&quot;&gt;&lt;button class=&quot;button&quot;&gt;ON&lt;/button&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;GPIO 3 - State off&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;/3/on&quot;&gt;&lt;button class=&quot;button&quot;&gt;ON&lt;/button&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;GPIO 4 - State off&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;/4/on&quot;&gt;&lt;button class=&quot;button&quot;&gt;ON&lt;/button&gt;&lt;/a&gt;&lt;/p&gt; &lt;/body&gt;&lt;/html&gt;)rawliteral&quot;; void notFound(AsyncWebServerRequest *request) { request-&gt;send(404, &quot;text/plain&quot;, &quot;Not found&quot;); } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFiManager wm; if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println(&quot;WiFi Failed!&quot;); return; } bool res; // res = wm.autoConnect(); // auto generated AP name from chipid // res = wm.autoConnect(&quot;AutoConnectAP&quot;); // anonymous ap res = wm.autoConnect(&quot;AutoConnectAP&quot;,&quot;password&quot;); // password protected ap if (!res) { Serial.println(&quot;Failed to connect&quot;); // ESP.restart(); } else { // if you get here you have connected to the WiFi Serial.println(&quot;connected...yeey :)&quot;); } Serial.println(); Serial.print(&quot;IP Address: &quot;); Serial.println(WiFi.localIP()); // Send web page with input fields to client server.on(&quot;/&quot;, HTTP_GET, [](AsyncWebServerRequest *request){ request-&gt;send_P(200, &quot;text/html&quot;, index_html); }); // Send a GET request to &lt;ESP_IP&gt;/get?input1=&lt;inputMessage&gt; server.on(&quot;/get&quot;, HTTP_GET, [] (AsyncWebServerRequest *request) { String inputMessage; String inputParam; // GET input1 value on &lt;ESP_IP&gt;/get?input1=&lt;inputMessage&gt; if (request-&gt;hasParam(PARAM_INPUT_1)) { inputMessage = request-&gt;getParam(PARAM_INPUT_1)-&gt;value(); inputParam = PARAM_INPUT_1; } // GET input2 value on &lt;ESP_IP&gt;/get?input2=&lt;inputMessage&gt; else if (request-&gt;hasParam(PARAM_INPUT_2)) { inputMessage = request-&gt;getParam(PARAM_INPUT_2)-&gt;value(); inputParam = PARAM_INPUT_2; } // GET input3 value on &lt;ESP_IP&gt;/get?input3=&lt;inputMessage&gt; else if (request-&gt;hasParam(PARAM_INPUT_3)) { inputMessage = request-&gt;getParam(PARAM_INPUT_3)-&gt;value(); inputParam = PARAM_INPUT_3; } else { inputMessage = &quot;No message sent&quot;; inputParam = &quot;none&quot;; } Serial.println(inputMessage); request-&gt;send(200, &quot;text/html&quot;, &quot;HTTP GET request sent to your ESP on input field (&quot; + inputParam + &quot;) with value: &quot; + inputMessage + &quot;&lt;br&gt;&lt;a href=\&quot;/\&quot;&gt;Return to Home Page&lt;/a&gt;&quot;); }); server.onNotFound(notFound); server.begin(); } void loop() { } </code></pre> <p>I tried different version of WiFiManager but still it doesn't work.</p>
<p>As the error messages tell you, there are two declarations of <code>HTTP_OPTIONS</code> via two includes. Apparently you cannot use these at the same time.</p> <p>&quot;WiFiManager.h&quot; has the <code>enum HTTPMethod</code> that has these constants.</p> <p>And &quot;ESPAsyncWebServer.h&quot; has another declaration of the same constants.</p> <p>You might need to read their documentation to learn whether work-arounds are possible.</p>
90303
|wifi|arduino-nano-33-iot|
Why does Arduino Nano 33 IoT always choose the weakest WiFi BSSID?
2022-07-26T08:54:23.617
<p>I have an Arduino Nano 33 IoT configured to connect to my WiFi network with a pretty straightforward code:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;WiFiNINA.h&gt; int status = WL_IDLE_STATUS; status = WiFi.status(); while (status != WL_CONNECTED) { status = WiFi.begin(ssid, pass); if (status == WL_CONNECTED) break; delay(5000); } </code></pre> <p>My problem is that in an environment with multiple access points sharing the same SSID (roaming environment) my Arduino is constantly connecting to the weakest one of the access points.</p> <p>I verified with WiFi Explorer on my laptop that multiple access points are in reach at the same location where the Arduino is placed and for some reason my Arduino decides to connect to the base station with BSSD ending <strong>:CA:81</strong>, which is paradoxly the weakest one:</p> <p><a href="https://i.stack.imgur.com/uF4Cg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uF4Cg.png" alt="WiFi explorer" /></a></p> <p>Is there a way to address this issue?</p>
<p>On Nano 33 IoT the WiFi network adapter is NINA esp32 module with Arduino's nina-fw. nina-fw is written with the use of ESP-IDF framework by the esp32 manufacturer Espressif.</p> <p>To connect to an AP the ESP-IDF has <a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv419esp_wifi_set_config16wifi_interface_tP13wifi_config_t" rel="nofollow noreferrer">a configuration function</a>, which takes a structure with settings. One of the settings is wifi_scan_method and <a href="https://github.com/arduino/nina-fw/blob/c84aa3406717af771653733fb9c3480bdf5e1a64/arduino/libraries/WiFi/src/WiFi.cpp#L188" rel="nofollow noreferrer">nina-fw uses</a> WIFI_FAST_SCAN. The alternative is WIFI_ALL_CHANNEL_SCAN.</p> <blockquote> <p>WIFI_FAST_SCAN Do fast scan, scan will end after find SSID match AP</p> </blockquote> <p>There is no simple solution for this. I don't know why they changed the setting. If it should be configurable then the firmware and the WiFiNINA library have to change to support it.</p> <p>Or you can get the sources of the firmware, change the setting, build the firmware (it is not trivial) and flash it to NINA on your Nano.</p>
90308
|shields|pcb-design|prototype|
Using prototype PCBs as Arduino shield
2022-07-26T16:46:30.460
<p>Is is possible to use prototype PCBs (PCB with grid of unconnected holes with copper around them, usually with pitch 2.54 mm) as Arduino shield, when they are fitted with appropriate pin headers?</p> <p>I am asking this question because I am not sure whether the Arduino UNO pin headers (which are split) will fit to the headers on the prototype PCB where I will “leave out” one pin on the header.</p> <p>(Yes, I ho not have a Arduino board to try it out now.)</p>
<p>For the UNO style boards, no it's not possible. The digital headers have a 0.16 inch gap between them which offsets one set of headers 0.06&quot; from the holes in the shield.</p> <p>For this reason you can buy specific Arduino prototyping shields that have the headers in the right locations.</p>
90316
|array|loop|keypad|char|
Char array filling with blanks
2022-07-27T18:25:17.923
<p>When I run this code, my <code>pin</code> and <code>pinCheck</code> arrays are not being filled with the results of <code>keypad.getKey()</code>. If I print the value at each index, the result is blank. As far as I can tell, I am either not writing a char to the array, I am misreading the array when it comes time to print to the serial monitor, or <code>.getKey()</code> only works in the main or loop functions.</p> <pre><code>#include &lt;Key.h&gt; #include &lt;Keypad.h&gt; void armDisarm(void); boolean array_cmp(char, char, int, int); bool isArmed = 0; char pin[3]; char pinCheck[3]; const byte ROWS = 4; // number of rows const byte COLS = 4; // number of columns char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'#','0','*','D'} }; byte rowPins[ROWS] = {9, 8, 7, 6}; // row pinouts of the keypad R1 = D8, R2 = D7, R3 = D6, R4 = D5 byte colPins[COLS] = {5, 4, 3, 2}; // column pinouts of the keypad C1 = D4, C2 = D3, C3 = D2 Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); void setup() { Serial.begin(9600); } void loop() { if (isArmed == 1) { Serial.println(&quot;SYSTEM ARMED! ENTER PIN TO DISARM!&quot;); } else { Serial.println(&quot;SYSTEM DISARMED! ENTER PIN TO ARM!&quot;); } armDisarm(); } void armDisarm(void) { while(true) { if (isArmed == 0) { for (int i = 0; i &lt; 4;) { if (keypad.getKey() == NO_KEY) { continue; } pin[i] = keypad.getKey(); Serial.println(pin[i]); i++; } isArmed = 1; return; } else if (isArmed == 1) { for (int j = 0; j &lt; 4;) { if (keypad.getKey() == NO_KEY) { continue; } pinCheck[j] = keypad.getKey(); Serial.println(pin[j]); j++; } for (int k = 0; k &lt; 4; k++) { if(pinCheck[k] != pin[k]) { isSame = 0; break; } else { isSame = 1; } } if (array_cmp(pin, pinCheck, sizeof(pin), sizeof(pinCheck)) == 1) { Serial.println(&quot;same pin&quot;); //used for bebugging isArmed = 0; return; } else { Serial.println(&quot;INCORRECT PIN! CLAYMORE ROOMBA DEPLOYED!&quot;); } } } } boolean array_cmp(char a[sizeof(pin)], char b[sizeof(pinCheck)], int len_a, int len_b) { int n; // if their lengths are different, return false if (len_a != len_b) { return false; } // test each element to be the same. if not, return false for (n = 0 ;n &lt; len_a; n++) { if (a[n]!= b[n]) { return false; } } //ok, if we have not returned yet, they are equal :) return true; } </code></pre>
<p>As an addition ToEdgar Bonets answer. I should warn you that your code keeps adding position in as each time you check array you are increasing the value of i. As a result you are filling arrays with NO_KEY.</p> <p>Also having have build a security alarm on arduino before (Or shouldnt we know thats what you are doing?) I should warn you that waiting for Keyboard inputs mean that you are not checking tamper or alarm even when its armed because you are stucked inside nonloop function waiting for imput. I have personally made input a global struct</p> <pre><code>struct foo{ char digits[4]; byte digit=0; } pinCode; </code></pre> <p>You can either take instance of the struct as a parameter to your function or because its global use it internaly.</p> <pre><code>bool addDigit(char button){ /*here deal with many potential inputs*/ </code></pre> <p>you can then inside your function assign the button pressed as</p> <pre><code>pinCode.digits[pinCode.digit]=button; pinCode.digit++; </code></pre> <p>if you are passing the instance of the struct as a pointer then it will change to</p> <pre><code>pinCode-&gt;digits[pinCode-&gt;digit]=button; pinCode-&gt;digit++; </code></pre> <p>you can then inside this funtion test if password is confirmed (OK is pressed) and return true.</p> <p>While the end of the password isn't reached, just return false. SO within the loop you would have something like:</p> <pre><code>key = keypad.getKey(); if(key!=NO_KEY){ if(addDigit(key)) //Here take an action based on inputs } // Do all the other stuff alarm has to do </code></pre>
90321
|esp8266|wifi|sd-card|arduino-uno-wifi|
Read SD card on ATMEGA328 from ESP826
2022-07-28T02:37:00.160
<p>I have a ATMEGA328 with ESP826 (like this <a href="http://arduinolearning.com/hardware/atmega328-esp8266-arduino-board.php" rel="nofollow noreferrer">http://arduinolearning.com/hardware/atmega328-esp8266-arduino-board.php</a>) and can successfully send information from the ATMEGA328 to the ESP826 via serial. I can also record information from the ATMEGA328 to SD card. What I would like to do is read data from the SD card with the ESP826 so I can upload it to a server..</p> <p>When I try to connect directly:</p> <pre><code>#include &lt;ESP8266WiFi.h&gt; #include &lt;SPI.h&gt; #include &lt;SD.h&gt; File myFile; void setup() { Serial.begin(115200); delay(10); Serial.print(&quot;Initializing SD card...&quot;); if (!SD.begin(10)) { Serial.println(&quot;initialization failed!&quot;); return; } myFile = SD.open(&quot;/&quot;); printDirectory(myFile, 0); Serial.println(&quot;done!&quot;); } void loop(){ } void printDirectory(File dir, int numTabs) { while (true) { File entry = dir.openNextFile(); if (! entry) { // no more files break; } for (uint8_t i = 0; i &lt; numTabs; i++) { Serial.print('\t'); } Serial.print(entry.name()); if (entry.isDirectory()) { Serial.println(&quot;/&quot;); printDirectory(entry, numTabs + 1); } else { // files have sizes, directories do not Serial.print(&quot;\t\t&quot;); Serial.println(entry.size(), DEC); } entry.close(); } } </code></pre> <p>It doesn't find the card. This is regardless of whether I have pins 1&amp;2 ON or not.</p> <p>Is there any way to write to the SD card using the ATMEGA328 and read that from the ESP826 (to send the files to the cloud)?</p>
<p>Have you consider something like nodeMCU? Is there a reason why you using such a complicated board? This would enable you to connect your SD card reader directly to nodeMCU, which can read the data from same inputs as atmega328 (watch for voltage differences) including the sensors which has the capability of uploading data to the cloud without the need of additional MCU, while making debugging far easier.</p> <p>I know that I am going to get dislikes here, but it looks to me like one of those cases when you connect two things that would work better of alone, making something does doesn't do either ones job very well. Maybe you can get a refund... If not contact your card issuer for &quot;Cardholder not present&quot; claim that bot VISA and Master card have.</p> <p>Is there any reason why wouldn't standard nodeMCU be enough for your project? (probably superior)</p> <p>If its not enough:</p> <p>If you connect node-mcu (5-15 Eur/Pounds/Dolars) and a nano (About half of the price) on a breadboard and connect them together via (software) serial pin, (using jumper cables and resistive divider), you can program them without messing with pointless dip switches and learn something usefull for future projects. latter you can replace nano for 3V3 pro miny to remove even the divider. There is this absurd idea from Arduino core team developers of using superiour Esp32 MCU as a secondary tool to inferiour ATMEGA328, while logically you should do the opposite. This is amplified by the fact that I would personaly consider Esp8266 core arduino libraries superior to those made for atmel... You might even find that the 2-3MB FS you can create on ModeMCU might be enough without the need of SD card.</p> <p>I had a quick look through the site and a combination defaulting to http and nonstandard hardware, combined with low standard of explanation, <strong>But what I find really imoral is harvesting excessive number of domain names on a similar subject</strong> which could have been used for other projects makes me think if these tutorials are designed to increase the sales of badly designed boards... I would recommend you to change the tutorial source...</p>
90329
|c++|class|
Invalid use of non-static member function
2022-07-28T18:59:13.730
<p>In order to explain my problem I used 3 classes: <code>Actions</code>, <code>Triggers</code>, and <code>Combine</code>.</p> <p><code>Actions</code> simulates an action function, that is defined externally.</p> <p><code>Triggers</code> has that function that needed to be executed.</p> <p><code>Combine</code> combines <code>Actions</code> and <code>Triggers</code>.</p> <p>Now, <code>void combine_funcs()</code> is a member function of <code>Combine</code> class, when the match between <code>Triggers</code> and <code>Actions</code> happen -&gt; passing a function to be executed.</p> <p>Here <code>void combine_funcs()</code> is show with <code>std::bind</code>, but is was also tested straight foreward.</p> <p>Error outsput is given below code.</p> <pre><code>class Actions { typedef void (*cb_func)(uint8_t resaon); private: cb_func exter_func; public: void get_external_func(cb_func func) { exter_func = func; } void callAction(uint8_t i) { exter_func(i); } }; class Triggers { public: void this_is_external_func(uint8_t i) { Serial.println(i); } }; class Combine { public: Actions a; Triggers b; void combine_funcs() { a.get_external_func(std::bind(&amp;Triggers::this_is_external_func, this,std::placeholders::_1)); } void loop() { if (millis() &gt; 10000) { a.callAction(); } } }; Combine combo; void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println(&quot;Start!&quot;); combo.combine_funcs(); } void loop() { // put your main code here, to run repeatedly: combo.loop(); } </code></pre> <p>Compilation output:</p> <pre><code>/Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino: In member function 'void Combine::combine_funcs()': sketch_jul26a:36:34: error: cannot convert 'std::_Bind_helper&lt;false, void (Triggers::*)(unsigned char), Combine*, const std::_Placeholder&lt;1&gt;&amp;&gt;::type' to 'Actions::cb_func' {aka 'void (*)(unsigned char)'} 36 | a.get_external_func(std::bind(&amp;Triggers::this_is_external_func, this,std::placeholders::_1)); | ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | std::_Bind_helper&lt;false, void (Triggers::*)(unsigned char), Combine*, const std::_Placeholder&lt;1&gt;&amp;&gt;::type /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:9:34: note: initializing argument 1 of 'void Actions::get_external_func(Actions::cb_func)' 9 | void get_external_func(cb_func func) | ~~~~~~~~^~~~ /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino: In member function 'void Combine::loop()': sketch_jul26a:42:20: error: no matching function for call to 'Actions::callAction()' 42 | a.callAction(); | ^ /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:13:8: note: candidate: 'void Actions::callAction(uint8_t)' 13 | void callAction(uint8_t i) | ^~~~~~~~~~ /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:13:8: note: candidate expects 1 argument, 0 provided exit status 1 cannot convert 'std::_Bind_helper&lt;false, void (Triggers::*)(unsigned char), Combine*, const std::_Placeholder&lt;1&gt;&amp;&gt;::type' to 'Actions::cb_func' {aka 'void (*)(unsigned char)'} </code></pre> <p><strong>EDIT_1 : Change <code>Combine</code> class to inherete other classes</strong></p> <pre><code>class Combine : public Actions, Triggers { public: void combine_funcs() { get_external_func(this_is_external_func); } void loop() { if (millis() &gt; 10000) { callAction(13); } } </code></pre> <p>yeilds same error:</p> <pre><code>/Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino: In member function 'void Combine::combine_funcs()': sketch_jul26a:33:23: error: invalid use of non-static member function 'void Triggers::this_is_external_func(uint8_t)' 33 | get_external_func(this_is_external_func); | ^~~~~~~~~~~~~~~~~~~~~ /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:22:8: note: declared here 22 | void this_is_external_func(uint8_t i) | ^~~~~~~~~~~~~~~~~~~~~ /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino: At global scope: sketch_jul26a:60:6: error: redefinition of 'void setup()' 60 | void setup() | ^~~~~ /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:46:6: note: 'void setup()' previously defined here 46 | void setup() | ^~~~~ sketch_jul26a:68:6: error: redefinition of 'void loop()' 68 | void loop() | ^~~~ /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:54:6: note: 'void loop()' previously defined here 54 | void loop() | ^~~~ exit status 1 invalid use of non-static member function 'void Triggers::this_is_external_func(uint8_t)' }; </code></pre>
<p>The problem is, that the return type of bind is not the same type as the type of the original function so you can't set it with <code>void get_external_func(cb_func func)</code>.</p> <p>But it looks like in X-&gt;Y problem. If you do OOP, use objects.</p> <p>I take the sketch in the question as a test so I want comment on other parts and how to do them properly. I just made minimal changes to pass the object and call the method (member function) with the object.</p> <pre><code> class Triggers { public: void func(uint8_t i) { Serial.println(i); } }; class Actions { Triggers* trigers; public: void set_triggers(Triggers* t) { trigers = t; } virtual void callAction(uint8_t i) { trigers-&gt;func(i); } }; class Combine { public: Actions a; Triggers b; void combine_funcs() { a.set_triggers(&amp;b); } void loop() { if (millis() &lt; 10000) { a.callAction(1); } } }; Combine combo; void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println(&quot;Start!&quot;); combo.combine_funcs(); } void loop() { // put your main code here, to run repeatedly: combo.loop(); } </code></pre>
90331
|serial|esp32|
Using ESP32 GPIO, Serial.printf(...) prints weird characters when input is larger than 12 characters
2022-07-28T20:20:58.117
<p>Learning C with the Freenove WSP32-WROVER starter kit and there's an issue I cannot find an answer to. Using the provided code to input some data with UART, it would seem to have a strange behavior whenever I input string that is larger than 12 characters. Under 12, everything is fine.</p> <pre><code>/********************************************************************** Filename : SerialRW Description : Use UART read and write data between ESP32 and PC. Auther : www.freenove.com Modification: 2020/07/11 **********************************************************************/ String inputString = &quot;&quot;; //a String to hold incoming data bool stringComplete = false; // whether the string is complete void setup() { Serial.begin(9600); Serial.println(String(&quot;\nESP32 initialization completed!\n&quot;) + String(&quot;Please input some characters,\n&quot;) + String(&quot;select \&quot;Newline\&quot; below and click send button. \n&quot;)); } void loop() { if (Serial.available()) { // judge whether data has been received char inChar = Serial.read(); // read one character inputString += inChar; if (inChar == '\n') { stringComplete = true; } } if (stringComplete) { Serial.printf(&quot;inputString: %s \n&quot;, inputString); inputString = &quot;&quot;; stringComplete = false; } } </code></pre> <p>The output of any larger than 12 characters string is sometimes a little bit different, but always seems to follow a similar pattern. For any 13 characters long string, I get :</p> <blockquote> <p>⸮⸮?</p> </blockquote> <p>The ouput changes if I add characters, for example 20 characters is this :</p> <blockquote> <p>D⸮⸮?</p> </blockquote> <p>I assume the unprintable character is a new line.</p> <p>The baud rate is set at the same value both in the code and in the serial monitor and I get the same results if I change the baud rate.</p> <p>Any explanation regarding this behaviour and how to avoid it would be most welcomed.</p>
<p>Change:</p> <pre class="lang-cpp prettyprint-override"><code>Serial.printf(&quot;inputString: %s \n&quot;, inputString); </code></pre> <p>to:</p> <pre class="lang-cpp prettyprint-override"><code>Serial.printf(&quot;inputString: %s \n&quot;, inputString.c_str()); </code></pre> <p><code>%s</code> expects a <code>const char *</code> which is not what <code>inputString</code> yields.</p> <p>What you're seeing in the difference between strings larger and smaller than 12 characters is down to whether or not <a href="https://github.com/espressif/arduino-esp32/blob/2.0.4/cores/esp32/WString.h#L307-L313" rel="nofollow noreferrer">small string optimization</a> is in use and how structures are passed in the ESP32's calling convention.</p>
90334
|esp8266|
Arduino/ESP8266 How to give users updated compiled code without using Arduino IDE
2022-07-28T21:19:23.063
<p>I have an Arduino project using an ESP8266 dev board.</p> <p>I want to be able to give users updates to my software in the future and I don't want them to have to download the code and the Arduino IDE to do so.</p> <p>Is there a way to take the compiled code from the Arduino IDE and use some other software to upload the compiled code to the ESP8266 dev board?</p>
<p>I figured it out! After getting some comments, <strong>I have decided to got with Option B.</strong></p> <p><strong>Firstly for both options, you will need to:</strong></p> <ol> <li>Using the Arduino IDE</li> <li>Under the &quot;Sketch&quot; tab; click &quot;Export compiled Binary&quot;, then click &quot;Show Sketch Folder&quot; (This is where your .bin file is)</li> </ol> <p><strong>Option A - Using an application</strong></p> <ol start="3"> <li>Download the ESPEasyFlasher code from below.</li> <li>You will probably have to open this with Visual Studio and compile it yourself.</li> <li>Make sure your .bin file and esptool.exe are included in your bin/release folder or wherever you want to have the &quot;FlashESP8266.exe&quot; program permanently.</li> <li>Run the &quot;FlashESP8266.exe&quot; program; select your com port, select your bin file, select the upload rate, then click flash.</li> </ol> <p>So you just have to make sure that your user has;</p> <ul> <li>Python installed</li> <li>Provide them a copy of the &quot;FlashESP8266.exe&quot;</li> <li>Provide them a copy of the &quot;esptool.exe&quot;</li> </ul> <p>I don't know if this will work the exact same for an ESP32 as I believe they have two .bin files...</p> <p>Resources:</p> <p><a href="https://nerdiy.de/en/howto-esp8266-mit-dem-esptool-bin-dateien-unter-windows-flashen/" rel="nofollow noreferrer">https://nerdiy.de/en/howto-esp8266-mit-dem-esptool-bin-dateien-unter-windows-flashen/</a></p> <p><a href="https://github.com/BattloXX/ESPEasyFlasher" rel="nofollow noreferrer">https://github.com/BattloXX/ESPEasyFlasher</a></p> <p><strong>Option B - Using OTA Update</strong></p> <p>3.You will need to first implement OTA Updates as @StarCat has pointed out in the comments.</p> <p>4.Navigate to the URL you implemented.</p> <p>5.Choose the File System, select your .bin file.</p> <p>6.Click Update FileSytem</p> <p>7.Should take a couple seconds or so and should be updated!</p> <p>I can confirm this works when your ESP8266 is set to host a Soft Access Point.</p> <p><strong>Koudos to @StarCat.</strong></p> <p>Resources:</p> <p><a href="https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html#web-browser" rel="nofollow noreferrer">https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html#web-browser</a></p>
90352
|power|esp32|espressif|
How to wire an ESP32-S2 Dev KitM-1 for power?
2022-08-01T13:33:44.483
<p>I'm putting an <a href="https://www.mouser.com/ProductDetail/Espressif-Systems/ESP32-S2-DevKitM-1?qs=DPoM0jnrROXzO8seOHN%252BOQ%3D%3D" rel="nofollow noreferrer">Espressif ESP32-S2 Dev KitM-1</a> into a project box. The box will have 12VDC power and a 5V buck converter for the Dev Kit.</p> <p>Do I need to use the USB port to power the Dev Kit or can I directly wire 5VDC to the 5V pin (and ground, of course) to power it?</p>
<p>The <a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/hw-reference/esp32s2/user-guide-devkitm-1-v1.html" rel="nofollow noreferrer">official documentation</a> has</p> <blockquote> <p>Power Supply Options</p> <p>There are three mutually exclusive ways to provide power to the board:</p> <ul> <li>Micro-USB Port, default power supply</li> <li>5V and GND pin headers</li> <li>3V3 and GND pin headers</li> </ul> </blockquote>
90366
|esp8266|esp|
ESP8266 SDCard initialization bug
2022-08-02T14:30:59.327
<p>I have an ESP8266 wich is connected to an SDCard module, an SHT21 sensor and an BMP280. The idea is that I want to log data from the sensors to the SD Card, but if I initialize the SD Card with SD.begin(chipSelect), all the data from sensors become NaN or random values. If I initialize it, it is logging only NaN on the sd card, so the card is working, and if I dont initialize it, I get good and normal values into the serial monitor. The Card Module is connected to D5,D6,D7,D8, and the two sensors are connected to D1 and D2, and all powered from 3v. Any idea? This is the code:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;SPI.h&gt; #include &lt;Sodaq_SHT2x.h&gt; #include &lt;Adafruit_BMP280.h&gt; Adafruit_BMP280 bmp; #include &lt;SD.h&gt; File myFile; float pressure; float temperature; float altimeter; float humidity; float dewPoint; float temperature2; float humidity2; float dewPoint2; int chipSelect = 5; float QNH = 1015; const int BMP_address = 0x76; int ledB = D4; int ledG = D3; int ledR = D0; void setup() { Serial.println(&quot;initialization done.&quot;); Wire.begin(); Serial.begin(9600); bmp.begin(BMP_address); Serial.println(&quot;PTHBox Logger&quot;); //Checking if SDCard is alive if (SD.begin(5)){ Serial.println(&quot;SD card is alive&quot;); }else{ Serial.println(&quot;SD card is ded&quot;); while(1); //halt program } //Checking the logfiles from the SDCard and deleting them if (SD.exists(&quot;/csv.txt&quot;)) { Serial.println(&quot;Removing csv.txt&quot;); SD.remove(&quot;/csv.txt&quot;); Serial.println(&quot;csv.txt is fresh and ready to log&quot;); } // Writing headers to csv.txt myFile = SD.open(&quot;/csv.txt&quot;, FILE_WRITE); if (myFile) // it opened OK { Serial.println(&quot;Writing headers to csv.txt&quot;); myFile.println(&quot;Altitude,Pressure,Temperature,Humidity,DewPoint&quot;); myFile.close(); Serial.println(&quot;Headers written&quot;); }else { Serial.println(&quot;Error opening csv.txt&quot;); } // Setting pinModes for the LED pinMode(D0, OUTPUT); pinMode(D3, OUTPUT); pinMode(D4, OUTPUT); //Set PWM frequency 500, default is 1000 //Set range 0~100, default is 0~1023 analogWriteFreq(500); analogWriteRange(100); } void loop() { // Testing the led analogWrite(ledR, 100); analogWrite(ledG, 0); analogWrite(ledB, 60); Serial.print(&quot;Humidity(%RH): &quot;); Serial.print(SHT2x.GetHumidity()); Serial.print(&quot; Temperature(C): &quot;); Serial.print(SHT2x.GetTemperature()); Serial.print(&quot; Dewpoint(C): &quot;); Serial.print(SHT2x.GetDewPoint()); pressure = bmp.readPressure()/100; //and conv Pa to hPa Serial.print(&quot; BMP PRESSURE&quot;); Serial.print(pressure); Serial.print(&quot; BMP ALT&quot;); Serial.println(bmp.readAltitude (QNH)); Serial.print(&quot; BMP TEMP&quot;); Serial.print(bmp.readTemperature()); // Assigning values to variables pressure = bmp.readPressure()/100; //and conv Pa to hPa temperature = (bmp.readTemperature()); //temperature from bmp altimeter = bmp.readAltitude (QNH); //QNH is local sea lev pressure humidity = (SHT2x.GetHumidity()); dewPoint = (SHT2x.GetDewPoint()); temperature2 = (SHT2x.GetTemperature()); // Writing the values to SDCARD myFile = SD.open(&quot;/csv.txt&quot;, FILE_WRITE); // if the file opened okay, write to it: if (myFile) { Serial.println(&quot;Writing to csv.txt&quot;); myFile.print(altimeter); myFile.print(pressure); myFile.print(temperature); myFile.print(humidity); myFile.println(dewPoint); myFile.close(); } else { Serial.println(&quot;error opening csv.txt&quot;); } delay(1000); } </code></pre>
<p>You're calling</p> <pre><code>if (SD.begin(5)){ </code></pre> <p>GPIO5 is not necessarily <code>D5</code>. Use the <code>D5</code> constant; it will evaluate to whatever GPIO number <code>D5</code> actually is. So,</p> <pre><code>if (SD.begin(D5)){ </code></pre> <p>Although you don't appear to be using the variable, you also have:</p> <pre><code>int chipSelect = 5; </code></pre> <p>which should be</p> <pre><code>int chipSelect = D5; </code></pre> <p>The difference between GPIO numbers and pin labels leads to problems for a lot of people. <code>GPIOx</code> is specific to the ESP8266 - it corresponds to a pin number and function on the actual chip; <code>Dx</code> is specific to the particular breakout board and is not always the same GPIO number (or the same between breakout boards).</p>
90399
|programming|keyboard|mouse|
Mouse.move: how do I move the mouse to the center of a screen?
2022-08-06T18:15:22.487
<p>I have a program operating in full screen mode. I would like to move the mouse to the center of the screen. Is this something I can do with the functionality of Mouse.h? <a href="https://www.arduino.cc/reference/en/language/functions/usb/mouse/" rel="nofollow noreferrer">https://www.arduino.cc/reference/en/language/functions/usb/mouse/</a></p> <p>Mouse.move moves fixed increments. maybe I should change the mouse start location in the computer program.</p> <p>my issue, is that the &quot;circuit playground&quot; is the primary interface, using the accelerator for position. Once the computer is running the software, the Arduino has to be centered to work properly.</p> <p>alternatively, is there a command I can send that could center the mouse?</p>
<p>There are two ways of working with HID mice - absolute and relative. The Arduino <code>Mouse</code> library only works in relative mode, but you want absolute.</p> <p>There's another library <strong><a href="https://github.com/NicoHood/HID" rel="nofollow noreferrer">https://github.com/NicoHood/HID</a></strong> which does do considerably more than the normal Arduino HID libraries - including &quot;Absolute Mouse&quot;.</p>
90408
|keyboard|
Why does keyboard.h add 136 to each key?
2022-08-08T02:46:25.837
<p>I want to create a custom keyboard mapping in the <a href="https://www.arduino.cc/reference/en/language/functions/usb/keyboard/" rel="nofollow noreferrer">official arduino keyboard library</a></p> <p>Why do the key definitions add 136 to each number?</p> <p><a href="https://github.com/arduino-libraries/Keyboard/blob/master/src/Keyboard_es_ES.h#L37-L42" rel="nofollow noreferrer">See Keyboard_es_ES.h on github</a></p> <pre><code>#define KEY_MASCULINE_ORDINAL (136+0x35) #define KEY_INVERTED_EXCLAMATION (136+0x2e) #define KEY_GRAVE (136+0x2f) #define KEY_N_TILDE (136+0x33) #define KEY_ACUTE (136+0x34) #define KEY_C_CEDILLA (136+0x31) </code></pre> <p>Looking at the <a href="https://www.asciitable.com/" rel="nofollow noreferrer">ascii table</a>, I see nothing special about value 136</p>
<p>It could be argued that this is an implementation detail of the library, that does not need to be documented. ;-) Anyway, here is the reason...</p> <p>The keyboard library uses a custom encoding scheme for representing <em>both</em> characters and keys. The public methods <code>press()</code>, <code>release()</code>, <code>write()</code>, <code>print()</code> and <code>println()</code> interpret the user-provided data according to this scheme. With this encoding, the interpretation of a byte depends on which of these three ranges it belongs to:</p> <ul> <li><p>Bytes in the range [0, 127] are understood to be ASCII characters. This is what enables you to write things like <code>Keyboard.println(&quot;Hello!&quot;);</code>. The library uses a keyboard layout array to map those characters to key scan codes¹, possibly modified by Shift or AltGr. You provide a pointer to this array as an argument to <code>begin()</code>.</p> </li> <li><p>Bytes in the range [128, 135] are interpreted as modifier keys, such as <code>KEY_LEFT_CTRL</code>, <code>KEY_RIGHT_SHIFT</code>, etc. Note that these keys do not have proper scan codes, as their state is transmitted to the host as a bit map (one byte for the eight keys) rather than as codes added to a list.</p> </li> <li><p>Bytes in the range [136, 255] are interpreted as raw scan codes in the range [0, 119], shifted by 136. This is what lets you actuate arbitrary keys such as <code>KEY_PRINT_SCREEN</code> or <code>KEY_LEFT_ARROW</code>. All scan codes of a standard full-size PC keyboard (ANSI 104 or ISO 105) lie in the range [4, 101]: you can access all of them, and even some more like <code>KEY_F24</code>.</p> </li> </ul> <p>Regarding the file Keyboard_es_ES.h: the codes in there are for keys that match ASCII characters in the US layout but not in the Spanish layout. The purpose is to ensure that every key of a ISO 105 keyboard can be actuated using either an ASCII character (like <code>Keyboard.press('a');</code>) or a <code>KEY_*</code> macro.</p> <p>¹ The USB standard calls them “usage codes”, but the old term “scan codes” seems more prevalent.</p>
90425
|arduino-uno|arduino-ide|vscode|
Using Visual Studio Code to program an Arduino
2022-08-10T07:43:44.077
<p>I had recently got an Arduino Uno and did quite a few programs on it. Now, I had always used <a href="http://arduino.cc/en/Main/ArduinoBoardUno" rel="nofollow noreferrer">Visual Studio Code</a> to do my C projects. So, is it possible to use Visual Studio Code to program an Arduino, but without the Arduino plugin available in Visual Studio Code?</p> <p>This might sound a bit weird, but I wanted to learn how to build those type of plugins from scratch. Are there some resources from where I could learn to do that? I searched through Google, but I couldn't find any answers.</p>
<p>You can write C++ file with the editor of your choice, include <code>avr/io.h</code> to manage Arduino I/O, and then compile with avr-gcc and upload with avrdude. This is what I do because I don't like working with the .ino sketch directory structure that hides away normal C++ code that you would use with any other microcontroller. (See <a href="https://arduino.stackexchange.com/questions/40393/what-is-the-relationship-of-an-arduino-ino-file-to-main-cpp">What is the relationship of an Arduino .ino file to main.cpp?</a>, <a href="https://arduino.stackexchange.com/questions/32619/why-does-an-ino-file-have-to-be-in-a-folder-of-the-same-name">Why does an `.ino` file have to be in a folder of the same name?</a>)</p> <p>Guide: <a href="https://create.arduino.cc/projecthub/milanistef/introduction-to-bare-metal-programming-in-arduino-uno-f3e2b4" rel="nofollow noreferrer">https://create.arduino.cc/projecthub/milanistef/introduction-to-bare-metal-programming-in-arduino-uno-f3e2b4</a></p>
90439
|arduino-uno|potentiometer|analog|
How to connect Draw wire encoder to Arduino Uno?
2022-08-11T06:28:35.660
<p>Hello Stack Community,</p> <p>I am new to Arduino, and I am trying to figure out how to connect a draw wire encoder to Arduino and collect data from it.</p> <p>I have attached a link of the product that I currently have, which also has datasheet, incase anyone needs more information.</p> <p><a href="https://www.kuebler.com/en/products/measurement/linear-measuring-systems/product-finder/product-details/A30" rel="nofollow noreferrer">https://www.kuebler.com/en/products/measurement/linear-measuring-systems/product-finder/product-details/A30</a></p> <p>I know that the encoder's output is through analog, but I am having trouble with connections as well.</p> <p>To summarize, how can I connect the encoder to Arduino Uno?</p> <p>Lastly, I am using the encoder to measure linear distance of linear actuators.</p>
<p>The simplest way is to use the version with potentiometer output:</p> <p><img src="https://i.stack.imgur.com/tQtif.png" alt="schematic" /></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2ftQtif.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>Connect the wiper to an analog input (A0 in the example), and use the analog reference voltage as &quot;supply&quot; voltage.</p>
90443
|usb|
Why modem driver is loaded and used from my linux machine in order to communicate with Arduino?
2022-08-11T09:50:22.823
<p>Once I plugin an arduino to my linux machine the following response is retrieved (via <code>dmesg</code>):</p> <pre><code>[ 7250.906241] perf: interrupt took too long (2504 &gt; 2500), lowering kernel.perf_event_max_sample_rate to 79750 [ 9517.599165] usb 1-3: new full-speed USB device number 5 using xhci_hcd [ 9517.749504] usb 1-3: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01 [ 9517.749510] usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=220 [ 9517.749513] usb 1-3: Manufacturer: Arduino (www.arduino.cc) [ 9517.749516] usb 1-3: SerialNumber: 7533131313335170A061 [ 9517.780753] cdc_acm 1-3:1.0: ttyACM0: USB ACM device [ 9517.781046] usbcore: registered new interface driver cdc_acm [ 9517.781047] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters </code></pre> <p>The last line from dmesg caught my attention:</p> <pre><code>[ 9517.781047] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters </code></pre> <p>Also as far as I remember in order to communicate with arduino my user needs to be into <code>dialout</code> group. Does that mean that a modem communication protocol is used in order to communicate from/to arduino in order to communicate via USB?</p>
<p>The answer to that is one of history.</p> <p>There was a time when the main purpose of the serial port (RS-232/UART) was to &quot;dial out&quot;; i.e. it had a serial connection to a modem, fax machine or a mainframe attached. Whatever it was, the primary function was to provide a data connection to the outer world, possibly incurring charges on a phone line. So, it is the other way round than you guessed: The computer communicated with the modem using a serial protocol named RS-232 or UART.</p> <p>Therefore, all serial ports have been secured to not allow access, except for the user group &quot;dialout&quot;. This has been retained as default, even for emulated and virtual serial ports -- like, for example, serial port over USB.</p>
90450
|arduino-uno|usb|
Is Arduino's USB communication protocol the same as USB modems use?
2022-08-11T19:31:47.490
<p>An Arduino Uno uses for the default USB communication either an FTDI chip in early versions or a microcontroller that emulates/replicates the FTDI chip communication.</p> <p>Is this type of USB communications the same as the Conexxant CX930xx modems use as well?</p> <p>What I want to achieve is to emulate the nessesary AT commands using the <a href="https://github.com/yourapiexpert/ATCommands" rel="nofollow noreferrer">ATCommand</a> library to replicate the modem's AT command instruction set. The things that I want to emulate are:</p> <ol> <li>The modem USB communication</li> <li>The subset of AT commands required for enabling/disabling an incomming call with Caller id</li> <li>Returning a &quot;fake&quot; incoming call with or without CallerId depending on the provided options from the PC via the AT commands</li> </ol> <p>For the last two I can somehow manage. But I don't know whether the existing FTDI chip/USB microcontroller uses the nessesary protocols that modems use as well. I mean would it be enough if I just replace the hardware and vendor ID or do I need to emulate another type of USB communication as well?</p> <p>The modem that I want to emulate is the: <a href="https://support.lenovo.com/us/en/solutions/pd003647-lenovo-usb-modem-overview" rel="nofollow noreferrer">https://support.lenovo.com/us/en/solutions/pd003647-lenovo-usb-modem-overview</a></p> <p>What I want to achieve is to fake an incomming call instead of using the actual modem. The reason why is, because I want to provide my own data towards modem-interfacing desktop application that use CallerId. Instead of using the actual modem I would love to have a fake one where I can emulate various scenarios.</p>
<p>Commonly USB modems use two layers of communication that are relevant for your issue.</p> <ol> <li><p>A virtual serial communication device, known as CDC/ACM, <a href="https://en.wikipedia.org/wiki/USB_communications_device_class" rel="nofollow noreferrer">Communication Device Class</a>, and Abstract Control Model, respectively.</p> </li> <li><p>Modem control protocol, known as <a href="https://en.wikipedia.org/wiki/Hayes_command_set" rel="nofollow noreferrer">Hayes command set</a>, vulgo &quot;AT command set&quot;, on top of this.</p> </li> </ol> <p>Both layers are generally independent of each other. You can use the virtual serial communication for any other purpose. And you can transport the Hayes commands and replies over any other communication stream.</p> <p>Most Arduino compatible devices reveal themselves as CDC/ACM to a PC, you can check this for example on Windows in the Hardware Manager. Therefore, the underlying transport layer exists for you.</p> <p>But to answer your concrete question: <strong>No</strong>, the second layer (AT commands) is missing. It is not necessary for the upload process or the serial monitoring.</p> <p>But you can write a sketch that implements that set of commands you would like use use for your application.</p>
90477
|programming|
Multiply char with float
2022-08-14T16:42:37.217
<p>I have a value for led brightness that is stored as an <code>unsigned char</code> (0-255)</p> <pre><code>unsigned char* colors[3]; colors[0] = 255; colors[1] = 0; colors[2] = 0; </code></pre> <p>I want to multiply a brightness percentage to that value.</p> <pre><code>float percent = 0.5; auto red_brightness = colors[0] * percent </code></pre> <p>Since <code>colors[0]</code> is of type <code>char</code> and <code>percent</code> is of type <code>float</code>. It gives error <code>Invalid operands of types 'unsigned char*' and 'float' to binary 'operator*'</code></p> <pre class="lang-cpp prettyprint-override"><code>unsigned char brightness; float percent; unsigned char* colors[3]; void setup() { Serial.begin(9600); colors[0] = 255; colors[1] = 0; colors[2] = 0; } void loop() { brightness = 127; float percent = (float)brightness / 255; float newRed = (float)colors[0] * percent; Serial.println(percent); Serial.print(&quot;red &quot;); Serial.print(newRed); Serial.println(&quot;&quot;); delay(1000); } </code></pre> <p>How can I multiply <code>colors[0]</code> (255) by <code>0.5</code> to get <code>127</code>?</p> <hr /> <h2>What I've tried</h2> <ol> <li>Cast <code>colors[0]</code> to a float or int</li> </ol> <pre><code> # invalid cast from type 'unsigned char' to type 'float' float newRed = (float)colors[0] * percent; </code></pre> <ol start="2"> <li>strtod</li> </ol> <p>Using <a href="https://www.convertdatatypes.com/Convert-char-Array-to-float-in-CPlusPlus.html" rel="nofollow noreferrer">this conversion website</a>, I've tried converting like so:</p> <pre><code> float tempColor = (float)strtod(colors[0],NULL); float newRed = tempColor * percent; </code></pre> <p>While this compiles, it always returns <code>0</code> (not <code>127</code> like I expect)</p> <pre class="lang-cpp prettyprint-override"><code>unsigned char brightness; float percent; unsigned char* colors[3]; void setup() { Serial.begin(9600); colors[0] = 255; } void loop() { brightness = 127; float percent = (float)brightness / 255; float tempColor = (float)strtod(colors[0],NULL); // &lt;- returns 0.00 Serial.print(&quot;tempColor&quot;); Serial.println(tempColor); delay(1000); } </code></pre> <p>How can I multiply <code>255</code> by <code>0.5</code> to get <code>~127</code> ?</p> <hr /> <h2>Solution</h2> <p>Thanks to the pointer by st2000 and <a href="https://learn.sparkfun.com/tutorials/data-types-in-arduino/defining-data-types" rel="nofollow noreferrer">this sparkfun article on datatypes</a></p> <p>I avoided floating point and char arrays and converted everything to <code>byte</code> and now my code works as expected. Thank you</p> <pre><code>byte brightness; byte percent; byte colors[3]; void setup() { Serial.begin(9600); colors[0] = 255; } void loop() { percent = 50; auto foobar = colors[0] * percent / 100; Serial.print(&quot;foobar: &quot;); Serial.println(foobar); </code></pre> <pre><code>11:12:19.833 -&gt; foobar: 127 </code></pre>
<p>You wrote:</p> <blockquote> <p>I have an led brightness that is stored as an <code>unsigned char</code> (0-255)</p> <pre class="lang-cpp prettyprint-override"><code>unsigned char* colors[3]; </code></pre> </blockquote> <p>This is not an array of <code>unsigned char</code>, this is an array of <strong>pointers</strong> to <code>unsigned char</code>. If you instead write</p> <pre class="lang-cpp prettyprint-override"><code>unsigned char colors[3]; </code></pre> <p>Everything should work as expected.</p> <p>But then, st2000 has very good advice on how to avoid expensive floating point operations.</p>
90486
|arduino-uno|button|
Arduino alternating between high and low signal without button press
2022-08-15T14:35:26.593
<p>I have connected my LCD with arduino uno. I am controlling contrast with the library and not the potentiometer. I am trying to read input from the button, it is connected to pin 9 of arduino. The resistor in the image is grounded, now arduino is not sensing signal from the button it keeps printing this even though in the timestamp below I have not touched the button. The resistor is 1k ohm.</p> <pre><code>20:03:30.808 -&gt; button not pressed 20:03:31.816 -&gt; button pressed 20:03:32.798 -&gt; button pressed 20:03:33.827 -&gt; button not pressed 20:03:34.821 -&gt; button pressed 20:03:35.849 -&gt; button not pressed 20:03:36.847 -&gt; button not pressed 20:03:37.842 -&gt; button pressed </code></pre> <p><a href="https://i.stack.imgur.com/4itwa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4itwa.png" alt="enter image description here" /></a></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;LiquidCrystal.h&gt; const int buttonNumPad1 = 9; int buttonNumPad1State = 0; int Contrast = 127.5; LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { Serial.begin(9600); pinMode(buttonNumPad1State, INPUT); analogWrite(6, Contrast); lcd.begin(16, 2); } void loop() { buttonNumPad1State = digitalRead(buttonNumPad1); if (buttonNumPad1State == HIGH){ Serial.println(&quot;button pressed&quot;); lcd.setCursor(0, 1); lcd.print(&quot;pressed&quot;); } else { Serial.println(&quot;button not pressed&quot;); } lcd.setCursor(0, 0); lcd.print(&quot;Hello&quot;); delay(1000); lcd.clear(); } </code></pre> <p>Top view of my breadboard</p> <p><a href="https://i.stack.imgur.com/nIV8D.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nIV8D.jpg" alt="enter image description here" /></a></p> <p>is it something related to? <a href="https://docs.arduino.cc/learn/microcontrollers/digital-pins" rel="nofollow noreferrer">https://docs.arduino.cc/learn/microcontrollers/digital-pins</a></p> <blockquote> <p>Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megohm in front of the pin. This means that it takes very little current to move the input pin from one state to another</p> </blockquote>
<p>Look at this breadboard image: <a href="https://i.stack.imgur.com/9K0tt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9K0tt.jpg" alt="breadboard with lines where the power rails are connected" /></a></p> <p>I have marked the power rail connections with green and red lines. Do you see, that they are not connected in the middle, right there where I've drawn the blue dotted line. Often the power rails of breadboards are not connected internally at that place. If that is the case for your breadboard you would need to bridge that gap with some jumper wires.</p> <p>If you don't do that, your button and pulldown resistor are not connected to anything but the digital input pin. So there is nothing setting the state of that pin (HIGH or LOW). Its just like you simply connected a wire to the digital input pin. And that's called a <strong>floating pin</strong>. It is not actively pulled in one direction, so any noise, that comes by, might change the state of the input pin.</p> <p>Make sure your button and pulldown resistor are actually electrically connected to ground. Bridge any gaps in the power rails, that your breadboard might have.</p>
90491
|programming|
Convert Int to HEX, HEX to string and to byte? General converting problem
2022-08-16T06:17:41.110
<p>Since Cpp is not my main language, I struggle to find the best way to convert between types for my needs. So my starting point is</p> <pre class="lang-cpp prettyprint-override"><code>struct can_frame { canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ __u8 can_dlc; /* frame payload length in byte (0 .. CAN_MAX_DLEN) */ __u8 data[CAN_MAX_DLEN] __attribute__((aligned(8))); }; </code></pre> <p>So first I needed it bo send to Serial as a hex string, so solution I've found and used was</p> <pre class="lang-cpp prettyprint-override"><code>String frame = &quot;CAN:&quot;; char dataString[1] = {0}; sprintf(dataString, &quot;%03X&quot;, can1Msg.can_id); frame += dataString; for (int i = 0; i &lt; can1Msg.can_dlc; i++) { // print the data char dataString[1] = {0}; sprintf(dataString, &quot;%02X&quot;, can1Msg.data[i]); frame += &quot; &quot; + String(dataString); } </code></pre> <p>Doesn't seem elegant byt it did the job.</p> <p>But then I needed to do some checking of ID and specific bytes So I've saved all String ins <code>String bytes[8]</code> So now I could something like</p> <pre class="lang-cpp prettyprint-override"><code>if (id == &quot;2A0&quot; &amp;&amp; bytes[0] == &quot;A0&quot;) { </code></pre> <p>And that was almost over, but then I realized that I need to do some checking of Integer number that is saved on 3 bytes. E.G <code>byte[2] + byte[3] + byte[4]</code> which would something like <code>0020A0</code> whih will be <code>8352</code> as an Int</p> <p>But converting things around gave all the problems such us <code>String to const char*</code> etc. I wanted to convert <code>__u8</code> to byte array so I can do checks and conversions and eventually convert it to string, but I've failed. Can anyone suggest best approach for this ?</p>
<p>The main problem that you are having is a lack of understanding in what &quot;hex&quot;, &quot;byte&quot;, etc are.</p> <p>You are trying to work with four data types (int, hex, string and byte) when in reality there are only two types: String and binary. Everything else is just a representation we as humans use to make easier sense of the binary data.</p> <p>You have a &quot;source&quot; type (<code>can1Msg.data</code>) which is, at one and the same time, binary, integer, hex and byte. The only thing it is not is <code>String</code> and you create that manually with your <code>sprintf</code> calls.</p> <p>To compare the third &quot;hex pair&quot; value in your data you simply:</p> <pre class="lang-cpp prettyprint-override"><code>if (can1Msg.data[2] == 0x42) { ... </code></pre> <p>That is, compare the 8-bit binary value stored in array slice 2 (arrays count from 0 so 2 is the third entry) with the binary value represented by the hex notation 42. The exact same thing can be done with:</p> <pre class="lang-cpp prettyprint-override"><code>if (can1Msg.data[2] == 66) { ... </code></pre> <p>66 is the decimal (base 10) equivalent of 0x42. You can also use binary or octal. These two are also exactly the same:</p> <pre class="lang-cpp prettyprint-override"><code>if (can1Msg.data[2] == 0102) { ... // octal if (can1Msg.data[2] == 0b01000010) { ... // binary </code></pre> <p>If you need to examine groups of bytes, such as if you have two bytes that form a 16-bit integer, you simply combine those two bytes into an integer, taking care to obey the correct <a href="https://www.freecodecamp.org/news/what-is-endianness-big-endian-vs-little-endian/" rel="nofollow noreferrer">endianness</a> of the values. For example if you have a 16 bit integer that is stored as <code>can1Msg.data[7]</code> and <code>can1Msg.data[8]</code> in <em>big endian</em> form, you can use:</p> <pre class="lang-cpp prettyprint-override"><code>uint16_t val = (can1Msg.data[7] &lt;&lt; 8) | can1Msg.data[8]; </code></pre> <p>Then simply compare the numeric (binary) integer value at will. All that line does is take the first 8 bit value and &quot;shift&quot; it 8 bits to the left to make it a 16 bit value with the lower 8 bits set to 0, then overlay the second value over those lower 8 zeroes, to make it a single 16-bit value.</p>
90492
|arduino-ide|ide|arduino-setup|
boards.txt - how to create sub-menu (NOT new board!!!)
2022-08-16T08:06:49.577
<p>Arduino 1.8.19</p> <p>Is it possible to create a sub-menu inside <code>boards.txt</code> that would allow having the boards grouped for example by the manufacturer? If it is possible, please provide an example or at least documentation for the language which is used for boards.txt.</p> <p>I <strong>don't</strong> want to add a new board.</p>
<p>No, it's not possible.</p> <p>The board menu (<a href="https://github.com/arduino/Arduino/blob/43b0818f7fa8073301db1b80ac832b7b7596b828/app/src/processing/app/Base.java#L1427" rel="nofollow noreferrer">defined here</a>) is a single flat menu with &quot;scroller&quot; added to it.</p> <p>To have multiple layers of menu you'd have to rewrite that entire part of the IDE.</p>
90500
|esp8266|
PSF WiFi module - Is it similar to ESP8266
2022-08-17T08:17:47.897
<p>Some products (as TUYA and SONOFF) are using a PSF wifi module. In this <a href="https://itead.cc/diy-kits-guides/psf-b04-application-guide/" rel="nofollow noreferrer">link</a>, PSF-B04 is reffers as ESP8285 design.</p> <p>does anyone flash a sketch to such chip ? should it be reffered as ESP8285 when selecting chip type in Arduino IDE ?</p> <p>Guy</p>
<p>ESP8285 is supported by esp8266 Arduino. You can select it in Tools menu.</p> <p><a href="https://i.stack.imgur.com/8xEqg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8xEqg.png" alt="enter image description here" /></a></p>
90504
|arduino-nano|interrupt|callbacks|
Share interrupt service between class
2022-08-17T15:51:24.850
<p>I would like to share interrupt routine between class. I followed this <a href="https://atadiat.com/en/e-arduino-trick-share-interrupt-service-routines-between-libraries-application/" rel="nofollow noreferrer">tutorial</a>.</p> <p>But I need to call a member function in callback function, I have the issue : <a href="https://i.stack.imgur.com/GApwK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GApwK.png" alt="enter image description here" /></a></p> <p>This is my code :</p> <p>Timer.h</p> <pre><code>static void (*__handleISR)(void); class Timer { public: Timer(); ~Timer(); static void init(); static void handleISR(void (*function)(void)); }; </code></pre> <p>Timer.cpp</p> <pre><code>Timer::Timer() { } Timer::~Timer() {} void Timer::init() { TCCR2A = 0; //default TIMSK2 = 0b00000001; // TOIE2 } ISR (TIMER2_OVF_vect) { // 256-6=250 --&gt; (250 x 16uS = 4mS) // Recharge le timer pour que la prochaine interruption se declenche dans 4mS TCNT2 = 6; __handleISR(); } </code></pre> <p>Device.h</p> <pre><code>class Device { public: Device(); private: void isr(); }; </code></pre> <p>Device.cpp</p> <pre><code>Device::Device() { Timer::init(); Timer::handleISR(isr); } void Device::isr() { // Do my stuff } </code></pre> <p>If I set function isr() static, it works. But I need to call member from Device in isr().</p> <p>How I can call non static member function ? Or another solution ?</p>
<p>This is not an Arduino specific question but a C++ question, and as such you might get more or better answers on <a href="https://stackoverflow.com/">StackOverflow</a>. Anyway, I'll suggest a possible solution.</p> <p>A member method always receives a pointer to its object as a hidden first argument that we know as <code>this</code>. Only via this argument such a method is able to access member attributes or member methods.</p> <p>A class method does not have this parameter.</p> <p>The function type you define is compatible only to functions or class methods.</p> <p>So you need to provide a pointer (or reference) to the <code>Device</code> object.</p> <p>I reduced your example and replaced the interrupt macro with something a standard C++ compiler accepts, as this is not part of the issue.</p> <p>Timer.h</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef TIMER_H #define TIMER_H #include &quot;Device.h&quot; class Timer { public: static void setCallback(void (*function)(Device*), Device*); }; #endif </code></pre> <p>Timer.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;Timer.h&quot; #define ISR(f) void f() static void (*_function)(Device*); static Device* _device; void Timer::setCallback(void (*function)(Device*), Device* device) { _function = function; _device = device; } ISR(TIMER2_OVF_vect) { _function(_device); } </code></pre> <p>Device.h</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef DEVICE_H #define DEVICE_H class Device { public: Device(); private: static void isr(Device* device); void isr(); }; #endif </code></pre> <p>Device.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;Device.h&quot; #include &quot;Timer.h&quot; Device::Device() { Timer::setCallback(isr, this); } void Device::isr(Device* device) { device-&gt;isr(); } void Device::isr() { // Do my stuff } </code></pre> <p><strong>If</strong> you don't need the <code>Device</code> object, you don't need a member method. Then go with a class method, as you already found out.</p>
90508
|serial|string|serial-data|data-type|c-string|
String() vs char for simple flow control
2022-08-17T22:39:58.403
<p>I am newbie in Arduino and writing a program where I want to control the flow by using Serial monitor input (PI controller). I've read that using String() although easier it is slower than using char. But to use char I would need more lines of code to convert the input into a string for comparison and more knowledge to make the program robust. For the control I will enter small strings like Ramp, Increase, Decrease, Lock, Stop and any other inputs will not be used. Generally, there are not going to be much inputs. The strings are basically going to be put into if-statements leading to functions.</p> <pre><code>if(Serial.available()){ string = Serial.readString() or some function to read out all the bytes of the string and return a char containing it; if(string=&quot;Ramp&quot;) { do_this(); } else_if(string=&quot;Increase&quot;){ do_that() } //If nothing matches, continue with code. } </code></pre> <p>Since I need to finish this project soon, I am wondering if it's going to increase the loop time significantly if I use String() or I shouldn't bother learning and using char right now (at a later stage, for sure).</p>
<p>Using <code>Serial.readString()</code> will make your program <em>very</em> slow. This is because <code>readString()</code> does not know when to stop reading. When the serial input buffer gets empty, it will wait just in case more characters may come later. Only when it times out does it return the string that it could read. The default timeout is one second, so your program will be unresponsive for a full second after receiving a command and before acting on it.</p> <p>You can shorten the timeout using <code>Serial.setTimeout()</code>, but this may make your program harder to test interactively by typing commands on a terminal emulator.</p> <p>I recommend you add a terminating character (say, <code>'\n'</code>) to each of your messages, then replace <code>Serial.readString()</code> with <code>Serial.readStringUntil()</code>. This method will return immediately when it finds the terminating character. Note that this character will <em>not</em> appear on the returned string object. <code>readStringUntil()</code> also obeys a timeout, but only when it cannot find the terminating character.</p> <p>Or you can learn the clean way to <a href="https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27" rel="nofollow noreferrer">read Serial on the Arduino</a>. Yes, it is a bit harder, but not a horrible thing to do.</p>
90519
|convert|
Converting 16bit to float
2022-08-18T21:07:21.087
<p>I am trying to communicate with AT30TS75A-MA8M-T with below code, the problem is converting the 16 bit output to float so I can read temp:</p> <p>Base on <a href="https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-8839-DTS-AT30TS75A-Datasheet.pdf" rel="nofollow noreferrer">data sheet</a> <a href="https://i.stack.imgur.com/bGVzS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bGVzS.png" alt="enter image description here" /></a> I suppose to remove first 5 bit in order to read correctly but I am not converting it correctly.</p> <p>Ex: (0b001001001100000 AND 0 b0111111111100000) = 0b1001001100000 0b1001001100000 &gt;&gt; 5 = 0b10010011 = 147</p> <pre><code> void Atemp::begin() { Wire.begin(); // Check if sensor temp sensor is avilable // if (mySensor.beginI2C() == false) // { // data[9] = 5; // Error Code // } // Set registor for two decimal Wire.beginTransmission(_i2cAddress); Wire.write(1); Wire.write(0b01100000); Wire.endTransmission(); } void Atemp::read() { Wire.beginTransmission(_i2cAddress); Wire.write(0); result = Wire.endTransmission(); // result is 0-4 if (result != 0) { data[9] = 5; // Error Code } result = Wire.requestFrom(_i2cAddress, (uint8_t)2); if (result != 2) { data[9] = 5; // Error Code } else { uint8_t part1 = Wire.read(); uint8_t part2 = Wire.read(); data[7] = part1; data[8] = part2; int16_t rawval = (part1 &lt;&lt; 8 | part2) ; // rawval &gt;&gt;= 6; float temp = rawval / 256.0f; floatconv(temp); } } </code></pre>
<p>Just a complement to Majenko's answer. The temperature register is set in such a way that you can interpret it in the same way irrespective of the selected resolution:</p> <pre class="lang-cpp prettyprint-override"><code>int16_t rawval = part1 &lt;&lt; 8 | part2; float temperature = rawval * (1/256.0); </code></pre>
90528
|serial|arduino-nano|softwareserial|gps|tinygps|
No GPS data Neo 6M DFRduino Nano
2022-08-19T14:09:31.800
<p>I checked several answers for same question but none of them help.</p> <p>I also changed the nano board and GPS module but without luck. I ran it outdoor.</p> <p><a href="https://arduino.stackexchange.com/questions/25901/not-getting-data-from-gps">This post question</a> had same issue except my date <strong>does not display the correct date and time</strong>.</p> <p>My connection:</p> <pre><code>vcc-&gt;5V rxd-&gt;d4 txd-&gt;d3 gnd-&gt;gnd </code></pre> <p>FullExample program from TinyGPS++, I get following types of entries</p> <pre><code>Sats HDOP Latitude Longitude Fix Date Time Date Alt Course Speed Card Distance Course Card Chars Sentences Checksum (deg) (deg) Age Age (m) --- from GPS ---- ---- to London ---- RX RX Fail ---------------------------------------------------------------------------------------------------------------------------------------- 0 100.0 ********** *********** **** 00/00/2000 00:00:00 152 ****** ****** ***** *** ******** ****** *** 324 0 0 0 100.0 ********** *********** **** 00/00/2000 00:00:00 230 ****** ****** ***** *** ******** ****** *** 486 0 0 0 100.0 ********** *********** **** 00/00/2000 00:00:00 308 ****** ****** ***** *** ******** ****** *** 648 0 0 0 100.0 ********** *********** **** 00/00/2000 00:00:00 384 ****** ****** ***** *** ******** ****** *** 810 0 0 0 100.0 ********** *********** **** 00/00/2000 00:00:00 463 ****** ****** ***** *** ******** ****** *** 972 0 0 0 100.0 ********** *********** **** 00/00/2000 00:00:00 541 ****** ****** ***** *** ******** ****** *** 1134 0 0 </code></pre> <p>NMEA read from serial</p> <pre><code>$GPGGA,,,,,,0,00,99.99,,,,,,*48 $GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30 $GPGSV,1,1,01,05,,,20*7F $GPGLL,,,,,,V,N*64 $GPRMC,,V,,,,,,,,,,N*53 $GPVTG,,,,,,,,,N*30 $GPGGA,,,,,,0,00,99.99,,,,,,*48 $GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30 $GPGSV,1,1,01,14,,,29*76 $GPGLL,,,,,,V,N*64 $GPRMC,,V,,,,,,,,,,N*53 $GPVTG,,,,,,,,,N*30 </code></pre> <p><strong>UPDATE:</strong></p> <p>I change the antenna. At some time I got this. From the GPGSV sentence I know that there are about 15 16 satellites in view but the FullExample only show 0.</p> <pre><code>$GPRMC,,V,,,,,,,,,,N*53 $GPVTG,,,,,,,,,N*30 $GPGGA,,,,,,0,00,99.99,,,,,,*48 $GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30 $GPGSV,4,1,15,04,,,31,07,,,33,09,,,34,11,,,30*74 $GPGSV,4,2,15,12,,,33,13,,,30,14,,,33,15,,,27*7D $GPGSV,4,3,15,16,,,33,19,,,34,20,,,30,21,,,33*70 $GPGSV,4,4,15,22,,,32,23,,,33,33,,,35*7B $GPGLL,,,,,,V,N*64 $GPRMC,,V,,,,,,,,,,N*53 $GPVTG,,,,,,,,,N*30 $GPGGA,,,,,,0,00,99.99,,,,,,*48 $GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30 $GPGSV,4,1,16,04,,,32,07,,,33,08,,,31,09,,,33*7A $GPGSV,4,2,16,11,,,29,12,,,33,13,,,30,14,,,34*73 $GPGSV,4,3,16,15,,,32,16,,,33,19,,,33,20,,,31*73 $GPGSV,4,4,16,21,,,33,22,,,33,23,,,34,33,,,35*7D $GPGLL,,,,,,V,N*64 </code></pre> <p>My idea now is to supply external power for the DFRduino Nano</p> <p>Any idea how I can continue. Should I changed to other type of gps module?</p>
<p>The ceramic antenna is the issue. I changed to the external 1.5GHz one. It got fix under 5 seconds</p>
90543
|bootloader|arduino-pro-micro|atmega32u4|programmer|
Is it possible to remove the bootloader while flashing using the bootloader?
2022-08-20T18:24:58.030
<p>The question is meant as in, can I lock myself out of the Arduino using the bootloader, if I flash a hex file that doesn't contain the bootloader?</p> <p>Or does the bootloader automatically add the flashed file after itself, so that it's never overwritten?</p> <p>The device in question is an Arduino Pro Micro (ATMega32u4). Asking, because I don't have an ISP available right now, and I have to flash pre-compiled hex files.</p>
<p>If you don't play around ISP programming and have not already been playing around with ISP programming, your bootloader is fine and will remain fine no matter what you try to upload. The bootloader has its own protected section, so it's not necessary to tack it onto your sketch code on every upload. The Pro Micro bootloader can't be updated via itself anyway.</p> <p>Worst case what you try to upload your precompiled binaries and they simply don't work.</p> <p>You <em>can</em> upload code that fails to respond to the 1200 baud touch request that is used to reset the board into the bootloader, which may make you think you've screwed up the board, but you haven't. The Pro Micro version of Caterina bootloader supports a double-tap reset for an 8-second upload window no matter what you've put (or tried putting) on the chip.</p> <p>Practically speaking, the existing bootloader is immutable and will always work for you until ISP becomes involved at some point.</p>
90561
|bootloader|
avr_boot change LED pin
2022-08-22T20:33:26.110
<p>I would like to know how can I change LED pin for <a href="https://github.com/zevero/avr_boot" rel="nofollow noreferrer">avr_boot</a> bootloader.</p> <p>I can see there is option in variants folder but in the manual it mention &quot;if using USE_LED adapt LED-pins in asmfunc.S&quot; which is not clear. I am using pin PC3 how do I write it.</p>
<p>Near the top of asmfunc.S, you have <a href="https://github.com/zevero/avr_boot/blob/v1.3.0/asmfunc.S#L9-L14" rel="nofollow noreferrer">these lines</a>:</p> <pre class="lang-lisp prettyprint-override"><code>; LED Pins #define DDR_SS _SFR_IO_ADDR(DDRD), 5 // SS pin (PIN, PORT) #define PORT_SS _SFR_IO_ADDR(PORTD), 5 #define DDR_PW _SFR_IO_ADDR(DDRD), 6 // Power pin (PIN, PORT) #define PORT_PW _SFR_IO_ADDR(PORTD), 6 </code></pre> <p>These define the “write” or “slave select” LED pin as PD5 (registers DDRD and PORTD, bit 5), and the “power” LED as PD6 (registers DDRD and PORTD, bit  6).</p> <p>These are the lines you have to change if using different pins. For example, pin PC3 is: registers DDRC and PORTC, bit 3.</p>
90567
|lora|
compress data with 8-4-2-1-BCD-Code
2022-08-23T20:46:06.223
<p>Hello I would like to optimise a few values for transmission via radio (LoRa) beforehand. I have a sensor number (1-255), temperature (00.00-99.99) and humidity. (00.00-99.99) I would like to transmit this data compressed as a byte array. I have already calculated that I need 5 bytes via BCD for this.</p> <p>How do I get my numbers mapped into the respective byte?</p> <pre><code>float temperature = 24.12; float humidity = 60.12; byte message[5]; void setup() { Serial.begin(9600); message[0] = 12; //sensor id 12 } void loop() { float temperature1 = floor(temperature); float temperature2 = (temperature - temperature1) * 100; Serial.println(temperature1, 0); Serial.println(temperature2, 0); message[1] //?? temperature1 message[2] //?? temperature2 float humidity1 = floor(humidity); float humidity2 = (humidity - humidity1) * 100; message[3] //?? humidity1 message[4] //?? humidity2 } </code></pre>
<p>This is my final solution with BCD-Code</p> <pre><code>int temperature1 = int(floor(temperature)); int temperature2 = int(round((temperature - temperature1) * 100)); uint8_t bcdTemperature1 = uint8_t((temperature1/10) &lt;&lt;4) | (temperature1 %10); uint8_t bcdTemperature2 = uint8_t((temperature2/10) &lt;&lt;4) | (temperature2 %10); message[0] = moduleUniqueidentifier; message[1] = bcdTemperature1; message[2] = bcdTemperature2; message[3] = uint8_t(ceil(humidity)); </code></pre>
90580
|pull-up|
Will I need the internal pullup resistor if no button is used?
2022-08-25T06:02:54.170
<p>Given I have two Arduinos that are supposed to primitively communicate with each other using digital pins. On Arduino Ar1, pin D13 is to be used as an input, connected to Ar2's D2 pin.</p> <p>Will I need to use the internal pullup resistor of Ar1 on pin 13, or is an outputted signal of LOW/HIGH already dragged to 0V/5V?</p>
<p>If you set a pin to output mode in Arduino, it is &quot;push-pull&quot;. This means, that any value, 0 or 1, is actively driven.</p> <p>Therefore, you do not need a pull-up or pull-down resistor on the receiving input.</p> <hr /> <p>You need such a resistor, only if the driver does not drive the voltage actively. For example, this is the case with buttons or switches, which simply open and close a contact.</p> <p>Some output modes exist like &quot;open-drain&quot; that only drive to GND at a value of 0, but do not drive the output pin at a value of 1. Such modes are not used if you call <code>pinMode()</code>.</p>
90588
|esp8266|programming|memory|serial-data|infrared|
memory leak w/ no Strings involved
2022-08-25T23:18:24.100
<p>I'm trying to read data being transferred via Infrared from my Smartmeter on my ESP8266 using the following sketch:</p> <pre><code>#include &lt;ESP8266WiFi.h&gt; #include &lt;ESP8266WebServer.h&gt; #include &lt;ESP8266HTTPUpdateServer.h&gt; #include &lt;Ticker.h&gt; #include &lt;AsyncMqttClient.h&gt; #ifndef STASSID #define STASSID &quot;mySSID&quot; #define STAPSK &quot;myPassword&quot; #endif #ifndef MQTT_HOST #define MQTT_HOST IPAddress(192, 168, 0, 100) #define MQTT_PORT 1883 #endif #ifndef IR #define SerialDebug Serial1 #define IR Serial #endif AsyncMqttClient mqttClient; Ticker mqttReconnectTimer; WiFiEventHandler wifiConnectHandler; WiFiEventHandler wifiDisconnectHandler; Ticker wifiReconnectTimer; const char* host = &quot;esp8266-webupdate&quot;; const byte firstByte = 0x7E; const byte lastByte = 0x7E; uint8_t i; ESP8266WebServer httpServer(80); ESP8266HTTPUpdateServer httpUpdater; void connectToWifi() { SerialDebug.println(&quot;Connecting to WiFi ...&quot;); WiFi.begin(STASSID, STAPSK); } void connectToMqtt() { SerialDebug.println(&quot;Connecting to MQTT ...&quot;); mqttClient.connect(); } void onWifiConnect(const WiFiEventStationModeGotIP&amp; event) { SerialDebug.println(&quot;Connected to Wi-Fi.&quot;); connectToMqtt(); } void onWifiDisconnect(const WiFiEventStationModeDisconnected&amp; event) { SerialDebug.println(&quot;Disconnected from Wi-Fi.&quot;); mqttReconnectTimer.detach(); wifiReconnectTimer.once(2, connectToWifi); } void onMqttConnect(bool sessionPresent) { SerialDebug.println(&quot;Connected to MQTT.&quot;); SerialDebug.print(&quot;Session present: &quot;); SerialDebug.println(sessionPresent); } void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { SerialDebug.println(&quot;Disconnected from MQTT.&quot;); if (WiFi.isConnected()) { mqttReconnectTimer.once(2, connectToMqtt); } } void array_to_string(byte array[], unsigned int len, char buffer[]) { for (unsigned int i = 0; i &lt; len; i++) { byte nib1 = (array[i] &gt;&gt; 4) &amp; 0x0F; byte nib2 = (array[i] &gt;&gt; 0) &amp; 0x0F; buffer[i*2+0] = nib1 &lt; 0xA ? '0' + nib1 : 'A' + nib1 - 0xA; buffer[i*2+1] = nib2 &lt; 0xA ? '0' + nib2 : 'A' + nib2 - 0xA; } buffer[len*2] = '\0'; } void setup() { SerialDebug.begin(115200); IR.begin(9600); SerialDebug.println(); SerialDebug.println(&quot;Booting Sketch...&quot;); wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); mqttClient.onConnect(onMqttConnect); mqttClient.onDisconnect(onMqttDisconnect); mqttClient.setServer(MQTT_HOST, MQTT_PORT); connectToWifi(); httpUpdater.setup(&amp;httpServer); httpServer.begin(); mqttClient.setWill(&quot;smartmeter/online&quot;, 0, true, &quot;no&quot;); } void loop() { httpServer.handleClient(); uint32_t timeout = 2000; int readCnt = 0; uint32_t start_time = millis(); byte tempChar = 0; byte *readMessage; uint32_t messageLen = 0; while ((tempChar != 0x7E) &amp;&amp; (millis() - start_time &lt; timeout)) { if (IR.available()) { tempChar = IR.read(); } } start_time = millis(); timeout = 1000; bool done = false; if (tempChar == firstByte) { // if first byte == 0x7E while ((millis() - start_time) &lt; timeout &amp;&amp; !done) { if (IR.available()) { tempChar = IR.read(); // second byte must be 0xA0 if(tempChar == 0xA0) { while ((millis() - start_time) &lt; timeout &amp;&amp; !done) { if (IR.available()) { tempChar = IR.read(); // 3rd byte tells the legth of the message readMessage = new byte[tempChar+2]; memset(readMessage, 0, tempChar+2); readMessage[0] = firstByte; readMessage[1] = 0xA0; readMessage[2] = tempChar; messageLen = ((uint32_t)(tempChar))+2; readCnt = 3; while ( readCnt &lt; messageLen &amp;&amp; ((millis() - start_time) &lt; timeout)) { // minimum len 120 chars for 0x7E format if (IR.available()) { readMessage[readCnt] = IR.read(); readCnt++; if(readCnt == tempChar+2 &amp;&amp; readMessage[readCnt-1] != lastByte) { // correct len but last byte not 0x7E done = true; SerialDebug.printf(&quot;Wrong end byte found - %d\n&quot;, readMessage[readCnt-1]); } else if(readCnt == tempChar+2) { // correct len and correct last byte done = true; char str[251] = &quot;&quot;; array_to_string(readMessage, readCnt, str); mqttClient.publish(&quot;smartmeter/raw&quot;, 0, false, str); } } } } } } } } } mqttClient.publish(&quot;smartmeter/online&quot;, 0, true, &quot;yes&quot;); char heap[6] = &quot;&quot;; itoa(ESP.getFreeHeap(), heap, 10); mqttClient.publish(&quot;smartmeter/freeHeap&quot;, 0, false, heap); } </code></pre> <p>I'm getting the encoded HEX-data published on my MQTT Topic as desired, the outputs length is 250 characters long (= 125 Bytes) which is correct:</p> <blockquote> <p>7ea07bcf000200231362b1e6e700db08534d536770075f626120000e32e62addedaede38e64c8c3173035a0a853851a28efc57f7fd76a9df59dbb152f796939328ff0f28df7f257d20b5cb2a458c4eb9188e2c1c251701c891244d859ed9c159714bb4451c090d9b1ed3bbb1fc89785ebafbf59ec4f9d540eb4c90d47e</p> </blockquote> <p>As I found out, the ESP's heap is decreasing by 100-300 by each iteration of the loop (data is being transmitted every second via Infrared from the power-grid Smartmeter) until the ESP will eventually be rebooted by the watchdog after like 5-8 minutes.</p> <p>I explicitly did not use String variables in the sketch but I legit cannot find the reason for the memory leak. Tried turning off wifi, webserver and mqtt one after each other which didn't actually made a difference.</p> <p>The heap-size stays at a constant level though when there is no data being received via the Infrared serial port, so I imagine something is fishy when storing the data in the byte array &quot;readMessage&quot;.</p> <p>Anything obvious that immediately pops into someones eye that I missed?</p>
<p>You do a <code>new</code> inside the loop</p> <pre><code> readMessage = new byte[tempChar+2]; </code></pre> <p>which causes the heap to be filled with <code>tempChar+2</code> bytes, but you never delete this.</p> <p>Try reusing this memory (making it a local, or make it 'dirty' global).</p> <p>Probably (not tested) the above line can be rewritten as:</p> <pre><code>byte readMessage[tempChar+2]; </code></pre>
90596
|arduino-uno|digitalwrite|
digitalWrite giving different output voltages between programs
2022-08-26T19:31:23.473
<p>I'm using an arduino uno R3 for lighting a few LEDs in response to coputer control. I've written two programs, the first to try an Object Oriented style, and the second to split up the code into more manageable chunks. They both implement the same function, turning one led on, then off and repeat for the other led. I'd also put 100uF capacitors between the anode and ground of each led for a fade effect. When running with the first sketch this works fine, but I noticed with the second sketch, the fade no longer works and the leds are much brighter. There was no change in hardware between sketches, and reverting to either doesn't change anything. On inspection with a multimeter there appears to be a large difference in output voltage (1.6v -&gt; 5.2v) between programs. I've tried changing pins and this seems to have no effect. Is it the code or have I missed something obvious with the hardware?</p> <p>Program 1</p> <pre><code>#include &quot;Arduino.h&quot; // create signal class class two_aspect_signal { //store pin numbers const int danger_aspect; const int clear_aspect; public: two_aspect_signal(int danger_pin, int clear_pin): danger_aspect(danger_pin), clear_aspect(clear_pin) {} void setup(){ //set to output pinMode(danger_aspect,OUTPUT); pinMode(clear_aspect,OUTPUT); } void danger(){ //turn red light on, green light off digitalWrite(danger_aspect,HIGH); digitalWrite(clear_aspect,LOW); } void cleaR(){ //turn red light off, green light on digitalWrite(danger_aspect,LOW); digitalWrite(clear_aspect,HIGH); } }; //create signal object two_aspect_signal sig(7,8); void setup() { } void loop() { //turn red light on, green off sig.danger(); delay(2000); //turn green light on, red light off sig.cleaR(); delay(2000); } </code></pre> <p>Program 2</p> <pre><code>#include &quot;sig2.h&quot; //create signal object two_aspect sig(7,8); void setup(){} void loop() { // set red light on, green off sig.danger(); delay(2000); // set green on, red off sig.cleaR(); delay(2000); } </code></pre> <p>Program 2 (sig2.cpp)</p> <pre><code>#include &quot;Arduino.h&quot; #include &quot;sig2.h&quot; two_aspect::two_aspect(int clear_pin, int danger_pin) { //set pins to output and store pinMode(danger_pin,OUTPUT); pinMode(clear_pin,OUTPUT); _danger_pin = danger_pin; _clear_pin = clear_pin; } void two_aspect::danger() { //set red light on, green off digitalWrite(_danger_pin,HIGH); digitalWrite(_clear_pin,LOW); } void two_aspect::cleaR() { //set green led on, red led off digitalWrite(_danger_pin,LOW); digitalWrite(_clear_pin,HIGH); } </code></pre> <p>Program 2 (sig2.h)</p> <pre><code>#ifndef sig2_h #define sig2_h #include &quot;Arduino.h&quot; class two_aspect { public: two_aspect(int clear_pin, int danger_pin); void danger(); void cleaR(); private: int _clear_pin; int _danger_pin; }; #endif </code></pre> <p>Please let me know if this should've been in the electronics forum, thanks for reading.</p>
<p>The difference is, that in your first sketch you never call <code>two_aspect_signal.setup()</code>, thus the pins are never set as output. By default pins are configured as inputs. Doing <code>digitalWrite()</code> while the pin is configured as input will enable or disable the internal pullup resistor of that pin.</p> <p>So in your first sketch you are powering the LEDs through the internal pullup resistor (if I correctly remember about 10kOhm). Thus they are rather dim. Also it takes some time for the capacitor to be charged through the big pullup resistor.</p> <p>In your second sketch you configure the pins as output. So the LEDs will now be actively driven through the pins output driver. It can provide way more current than the pullup resistor, thus the LEDs light up brigther. And the bigger current can also charge the capacitor in way less time (a time so small, that you don't even see it). Thus you don't see any fading (the fading is there, but just too fast for your eyes).</p> <p><strong>What to do know?</strong> You can of course just use the pullup resistor (and not configuring the pins as output). Or you can configure the pins as outputs and add a current limiting resistor between the pin and the LED/capacitor bundle. With your second sketch and the current circuit you are risking to damage the output drivers of that pin (through the LED current and through the high inrush current until the capacitor is charged). The sizing of that resistor depends on your needs. Make sure, that the current never exceeds 20mA (sustainable pin max current) (for 5V this would be R=U/I=5V/20mA=250Ohm as minimum resistance). The higher the resistance, the dimmer the LED will be and the longer the capacitor needs to charge. After that you can also change the capacitance. The higher the capacitance, the longer it will take to charge it (so longer fade effect).</p>
90635
|c++|
IF statement inside of a function call? Code help
2022-08-31T14:29:47.107
<p>I was browsing a library for steppers motors when I ran across this line of foreign-looking code:</p> <pre><code>digitalWrite(enable_pin, (enable_active_state == HIGH) ? LOW : HIGH); </code></pre> <p>Is this some kind of shortcut to tossing an if statement into a function call? I've never seen this before. What exactly does it do, and what is this particular arrangement of code called?</p> <p>Thanks!</p>
<p>You could look at this as an &quot;if expression&quot;, the correct term is &quot;conditional operator&quot; (C++ standard chapter 8.16). Many know it as &quot;ternary operator&quot; because it has three operands. You might already know the &quot;unary operator&quot; with one operand like the negation sign <code>-x</code>, or the &quot;binary operator&quot; with two operands like the addition <code>a + b</code>.</p> <p>This expression consists of:</p> <ul> <li>the first operand</li> <li>the operator <code>?</code></li> <li>the second operand</li> <li>the operator <code>:</code></li> <li>the third operand</li> </ul> <p>The first operator is evaluated and converted (if necessary) into a boolean.</p> <p>If the result is <code>true</code>, the second operand is evaluated and gives the value of the expression.</p> <p>If the result is <code>false</code>, the third operand is evaluated and gives the value of the expression.</p> <p>Only one of the second and third operands is evaluated. This is important, if you use operands with side effects, like function calls can have.</p> <p>This operator is often frowned upon. If used excessively, the source becomes easily unreadable. Many professional code style guide prohibit its use for this reason.</p> <p>In your case it could have been written more clearly as</p> <pre class="lang-cpp prettyprint-override"><code>if (enable_active_state == HIGH) { digitalWrite(enable_pin, LOW); } else { digitalWrite(enable_pin, HIGH); } </code></pre> <p>It outputs the inverted value of the variable <code>enable_active_state</code> at the pin <code>enable_pin</code>.</p> <p>Experienced Arduino users know that <code>HIGH</code> and <code>LOW</code> are represented in a way that are compatible with boolean values. Boolean inversions can be simpler expressed with the logical negation operator:</p> <pre class="lang-cpp prettyprint-override"><code>digitalWrite(enable_pin, !enable_active_state); </code></pre> <p>Anyway, the current compilers are commonly smart enough to generate the same machine code for each of the variants. Therefore, please write your source in the best way to express your intention. Anything else is &quot;premature optimization&quot;, which is a bad thing. But this is a completely other topic.</p>
90637
|esp32|temperature-sensor|temperature|
How to use the M117 temperature sensor from mysentech?
2022-08-31T15:42:56.640
<p>Anyone can help me decode the temperature of <a href="https://www-mysentech-com.translate.goog/productinfo/535226.html?_x_tr_sch=http&amp;_x_tr_sl=zh-CN&amp;_x_tr_tl=en&amp;_x_tr_hl=en&amp;_x_tr_pto=sc" rel="nofollow noreferrer">the M117 chip from mysentech.com</a>?</p> <p>I tried things, but I get a constant raw value of 0xFFFF, which becomes 1 once 2's complemented is applied.</p> <p>The chip shows up at the expected address (TEMP_SENSOR_ADDRESS is 0x45) during a scan operation of the I2C bus.</p> <pre class="lang-cpp prettyprint-override"><code> // Start I2C Transmission Wire.beginTransmission(TEMP_SENSOR_ADDRESS); // Select data register Wire.write(0x00); // Stop I2C Transmission Wire.endTransmission(); delay(300); // == Request for the raw temp 2 bytes Wire.requestFrom(TEMP_SENSOR_ADDRESS, 2); const size_t count = Wire.available(); log(&quot;%d bytes available&quot;, count); if (count!=2) { *ready = false; warn(&quot;I2c temp is not available&quot;); } else { *ready = true; // Get the raw data as the 16-bit big endian (MSB-LSB) byte data0 = Wire.read(); byte data1 = Wire.read(); const uint16_t raw = data0&lt;&lt;8 | data1; const int sign = raw&gt;&gt;15 == 1 ? -1 : 1; // Get the raw temperature as a 2's complement of the 16-bit (MSB-LSB) value const int16_t c2Raw = ~raw + 1; // Apply scale and offset temperature = sign * float(c2Raw)/256.0 + 40; log(&quot;raw: %04x (%d) | Raw 2's complement %04x (%d) | temperature: %f°C&quot;, raw, raw, c2Raw, c2Raw, temperature ); } </code></pre> <p><strong>[UPDATE | SEPT. 2nd 2022]</strong> Following the discussion I had with @jsoleta, my current code is as follows. But still getting FFFF AC. AC being the correct CRC for FFFF. Coud it be the result of a wiring issue of the component on our custom PCB?</p> <p>The logs:</p> <pre><code>b5725|—| Thermometer: Command: Writing to register command 0xCC44 b5725|—| Thermometer: Command byte 0: cc b5725|—| Thermometer: Command byte 1: 44 b5725|—| Thermometer: Command: register transmitted 2 bytes b5725|—| Thermometer: 3 bytes available b5725|—| Thermometer: Actually read 3 bytes: ff ff ac b5725|—| Thermometer: CRC matched: computed: ac == read: ac b5725|—| Thermometer: raw: ffff (65535) | Raw 2's complement 0001 (1) | temperature: 39.996094°C b5725|—| Thermometer: raw: ffff (65535) | temperature: 39.996094°C b5725|—| Thermometer: Transmitting board temperature 40.0°C over the RS-485 bus (raw is 799 - 0x031f) </code></pre> <p>The updated code:</p> <pre class="lang-cpp prettyprint-override"><code>loat I2cThermometer :: readTemperature(bool *ready) { float temperature = 0; log(&quot;Command: Writing to register command 0xCC44&quot;); // Start I2C Transmission Wire.beginTransmission(TEMP_SENSOR_ADDRESS); // Select data register 0x00, config 0x01 const uint16_t command = 0xcc44 // Wait for temperature measurement //0xf32d // Read status //0x611d // Measurement result set alarm ; byte * data = (byte*)&amp;command; Wire.write(data[1]); log(&quot;Command byte 0: %02x&quot;, data[1]); Wire.write(data[0]); log(&quot;Command byte 1: %02x&quot;, data[0]); // Stop I2C Transmission const auto readCount = Wire.endTransmission(); log(&quot;Command: register transmitted %d bytes&quot;, readCount); delay(15); // == Request for the raw temp 2 bytes + CRC Wire.requestFrom(TEMP_SENSOR_ADDRESS, 3); // 2-byte data + 1-byte CRC const size_t count = Wire.available(); log(&quot;%d bytes available&quot;, count); if (count!=3) { *ready = false; warn(&quot;No temp data is not available&quot;); } else { *ready = true; // Get the raw data as the 16-bit big endian (MSB-LSB) byte data[3]; const size_t r = Wire.readBytes(data, sizeof data); log(&quot;Actually read %d bytes: %02x %02x %02x&quot;, r, data[0], data[1], data[2]); const byte crc = MY_CRC8(data, 2); if (crc != data[2]) { warn(&quot;CRC mismatch: computed: %02x != read: %02x&quot;, crc, data[2]); } else { success(&quot;CRC matched: computed: %02x == read: %02x&quot;, crc, data[2]); } const uint16_t raw = *(uint16_t*)data; const int sign = raw&gt;&gt;15 == 1 ? -1 : 1; // Get the raw temperature as a 2's complement of the 16-bit big engdian (MSB-LSB) const int16_t c2Raw = ~raw + 1; // Apply scale and offset temperature = sign * float(c2Raw)/256.0 + 40; #if LOG_LEVEL &gt;= LOG_LEVEL_DEBUG log(&quot;raw: %04x (%d) | Raw 2's complement %04x (%d) | temperature: %f°C&quot;, raw, raw, c2Raw, c2Raw, temperature ); #endif #if LOG_LEVEL &gt;= LOG_LEVEL_DEBUG log(&quot;raw: %04x (%d) | temperature: %f°C&quot;, raw, raw, temperature ); #endif writeBoardTemperatureMessage(temperature); } if (!(*ready)) { #if LOG_LEVEL &gt;= LOG_LEVEL_INFO log(&quot;Temperature is not ready %d°C&quot;, temperature); #endif return temperature; } #if LOG_LEVEL &gt;= LOG_LEVEL_INFO log(&quot;Temperature is %d°C&quot;, temperature); #endif return temperature; } </code></pre>
<p>Ok, I found something weird. My code do work if I request the sensor every 4 seconds at max. But if the frequency is below that, it won't work.</p> <p>Will replace the sensor, rolling back to TMP112, as before.</p>
90671
|arduino-ide|ble|nrf52|
nRF52832 BLE "conn_handle" to disconnect the current connected devices
2022-09-05T07:08:53.227
<p>I'm working on <a href="https://www.adafruit.com/product/3406" rel="nofollow noreferrer">nRF52832 Bluefruit Adafruit Module</a>. I want the BLE connection to disconnect using a function and can call whenever required. But the issue is the disconnect function needs &quot;conn_handle&quot; to disconnect from the current connected Client.</p> <p>Can anyone help me find where I can get the &quot;conn_handle&quot; of the connected client?</p> <pre><code>/** * Callback invoked when a connection is dropped * @param conn_handle * @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h */ void disconnect_callback(uint16_t conn_handle, uint8_t reason) { (void) conn_handle; (void) reason; connection_num--; // Mark the ID as invalid int id = findConnHandle(conn_handle); // Non-existant connection, something went wrong, DBG !!! if ( id &lt; 0 ) return; // Mark conn handle as invalid prphs[id].conn_handle = BLE_CONN_HANDLE_INVALID; Serial.print(prphs[id].name); Serial.println(&quot; disconnected!&quot;); } </code></pre> <p>The below complete code is for &quot;Central Bleuart Multi&quot;-</p> <pre><code>/********************************************************************* This is an example for our nRF52 based Bluefruit LE modules Pick one up today in the adafruit shop! Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! MIT license, check LICENSE for more information All text above, and the splash screen below must be included in any redistribution *********************************************************************/ /* This sketch demonstrates the central API() that allows you to connect * to multiple peripherals boards (Bluefruit nRF52 in peripheral mode, or * any Bluefruit nRF51 boards). * * One or more Bluefruit boards, configured as a peripheral with the * bleuart service running are required for this demo. * * This sketch will: * - Read data from the HW serial port (normally USB serial, accessible * via the Serial Monitor for example), and send any incoming data to * all other peripherals connected to the central device. * - Forward any incoming bleuart messages from a peripheral to all of * the other connected devices. * * It is recommended to give each peripheral board a distinct name in order * to more easily distinguish the individual devices. * * Connection Handle Explanation * ----------------------------- * The total number of connections is BLE_MAX_CONNECTION (20) * * The 'connection handle' is an integer number assigned by the SoftDevice * (Nordic's proprietary BLE stack). Each connection will receive it's own * numeric 'handle' starting from 0 to BLE_MAX_CONNECTION-1, depending on the order * of connection(s). * * - E.g If our Central board connects to a mobile phone first (running as a peripheral), * then afterwards connects to another Bluefruit board running in peripheral mode, then * the connection handle of mobile phone is 0, and the handle for the Bluefruit * board is 1, and so on. */ /* LED PATTERNS * ------------ * LED_RED - Blinks pattern changes based on the number of connections. * LED_BLUE - Blinks constantly when scanning */ #include &lt;bluefruit.h&gt; // Struct containing peripheral info typedef struct { char name[16+1]; uint16_t conn_handle; // Each prph need its own bleuart client service BLEClientUart bleuart; } prph_info_t; /* Peripheral info array (one per peripheral device) * * There are 'BLE_MAX_CONNECTION' central connections, but the * the connection handle can be numerically larger (for example if * the peripheral role is also used, such as connecting to a mobile * device). As such, we need to convert connection handles &lt;-&gt; the array * index where appropriate to prevent out of array accesses. * * Note: One can simply declares the array with BLE_MAX_CONNECTION and use connection * handle as index directly with the expense of SRAM. */ prph_info_t prphs[BLE_MAX_CONNECTION]; // Software Timer for blinking the RED LED SoftwareTimer blinkTimer; uint8_t connection_num = 0; // for blink pattern void setup() { Serial.begin(115200); while ( !Serial ) delay(10); // for nrf52840 with native usb // Initialize blinkTimer for 100 ms and start it blinkTimer.begin(100, blink_timer_callback); blinkTimer.start(); Serial.println(&quot;Bluefruit52 Central Multi BLEUART Example&quot;); Serial.println(&quot;-----------------------------------------\n&quot;); // Initialize Bluefruit with max concurrent connections as Peripheral = 0, Central = 4 // SRAM usage required by SoftDevice will increase with number of connections Bluefruit.begin(0, 4); // Set Name Bluefruit.setName(&quot;Bluefruit52 Central&quot;); // Init peripheral pool for (uint8_t idx=0; idx&lt;BLE_MAX_CONNECTION; idx++) { // Invalid all connection handle prphs[idx].conn_handle = BLE_CONN_HANDLE_INVALID; // All of BLE Central Uart Serivce prphs[idx].bleuart.begin(); prphs[idx].bleuart.setRxCallback(bleuart_rx_callback); } // Callbacks for Central Bluefruit.Central.setConnectCallback(connect_callback); Bluefruit.Central.setDisconnectCallback(disconnect_callback); /* Start Central Scanning * - Enable auto scan if disconnected * - Interval = 100 ms, window = 80 ms * - Filter only accept bleuart service in advertising * - Don't use active scan (used to retrieve the optional scan response adv packet) * - Start(0) = will scan forever since no timeout is given */ Bluefruit.Scanner.setRxCallback(scan_callback); Bluefruit.Scanner.restartOnDisconnect(true); Bluefruit.Scanner.setInterval(160, 80); // in units of 0.625 ms Bluefruit.Scanner.filterUuid(BLEUART_UUID_SERVICE); Bluefruit.Scanner.useActiveScan(false); // Don't request scan response data Bluefruit.Scanner.start(0); // 0 = Don't stop scanning after n seconds } /** * Callback invoked when scanner picks up an advertising packet * @param report Structural advertising data */ void scan_callback(ble_gap_evt_adv_report_t* report) { // Since we configure the scanner with filterUuid() // Scan callback only invoked for device with bleuart service advertised // Connect to the device with bleuart service in advertising packet Bluefruit.Central.connect(report); } /** * Callback invoked when an connection is established * @param conn_handle */ void connect_callback(uint16_t conn_handle) { // Find an available ID to use int id = findConnHandle(BLE_CONN_HANDLE_INVALID); // Eeek: Exceeded the number of connections !!! if ( id &lt; 0 ) return; prph_info_t* peer = &amp;prphs[id]; peer-&gt;conn_handle = conn_handle; Bluefruit.Connection(conn_handle)-&gt;getPeerName(peer-&gt;name, sizeof(peer-&gt;name)-1); Serial.print(&quot;Connected to &quot;); Serial.println(peer-&gt;name); Serial.print(&quot;Discovering BLE UART service ... &quot;); if ( peer-&gt;bleuart.discover(conn_handle) ) { Serial.println(&quot;Found it&quot;); Serial.println(&quot;Enabling TXD characteristic's CCCD notify bit&quot;); peer-&gt;bleuart.enableTXD(); Serial.println(&quot;Continue scanning for more peripherals&quot;); Bluefruit.Scanner.start(0); Serial.println(&quot;Enter some text in the Serial Monitor to send it to all connected peripherals:&quot;); } else { Serial.println(&quot;Found ... NOTHING!&quot;); // disconnect since we couldn't find bleuart service Bluefruit.disconnect(conn_handle); } connection_num++; } /** * Callback invoked when a connection is dropped * @param conn_handle * @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h */ void disconnect_callback(uint16_t conn_handle, uint8_t reason) { (void) conn_handle; (void) reason; connection_num--; // Mark the ID as invalid int id = findConnHandle(conn_handle); // Non-existant connection, something went wrong, DBG !!! if ( id &lt; 0 ) return; // Mark conn handle as invalid prphs[id].conn_handle = BLE_CONN_HANDLE_INVALID; Serial.print(prphs[id].name); Serial.println(&quot; disconnected!&quot;); } /** * Callback invoked when BLE UART data is received * @param uart_svc Reference object to the service where the data * arrived. */ void bleuart_rx_callback(BLEClientUart&amp; uart_svc) { // uart_svc is prphs[conn_handle].bleuart uint16_t conn_handle = uart_svc.connHandle(); int id = findConnHandle(conn_handle); prph_info_t* peer = &amp;prphs[id]; // Print sender's name Serial.printf(&quot;[From %s]: &quot;, peer-&gt;name); // Read then forward to all peripherals while ( uart_svc.available() ) { // default MTU with an extra byte for string terminator char buf[20+1] = { 0 }; if ( uart_svc.read(buf,sizeof(buf)-1) ) { Serial.println(buf); sendAll(buf); } } } /** * Helper function to send a string to all connected peripherals */ void sendAll(const char* str) { Serial.print(&quot;[Send to All]: &quot;); Serial.println(str); for(uint8_t id=0; id &lt; BLE_MAX_CONNECTION; id++) { prph_info_t* peer = &amp;prphs[id]; if ( peer-&gt;bleuart.discovered() ) { peer-&gt;bleuart.print(str); } } } void loop() { // First check if we are connected to any peripherals if ( Bluefruit.Central.connected() ) { // default MTU with an extra byte for string terminator char buf[20+1] = { 0 }; // Read from HW Serial (normally USB Serial) and send to all peripherals if ( Serial.readBytes(buf, sizeof(buf)-1) ) { sendAll(buf); } } } /** * Find the connection handle in the peripheral array * @param conn_handle Connection handle * @return array index if found, otherwise -1 */ int findConnHandle(uint16_t conn_handle) { for(int id=0; id&lt;BLE_MAX_CONNECTION; id++) { if (conn_handle == prphs[id].conn_handle) { return id; } } return -1; } /** * Software Timer callback is invoked via a built-in FreeRTOS thread with * minimal stack size. Therefore it should be as simple as possible. If * a periodically heavy task is needed, please use Scheduler.startLoop() to * create a dedicated task for it. * * More information http://www.freertos.org/RTOS-software-timer.html */ void blink_timer_callback(TimerHandle_t xTimerID) { (void) xTimerID; // Period of sequence is 10 times (1 second). // RED LED will toggle first 2*n times (on/off) and remain off for the rest of period // Where n = number of connection static uint8_t count = 0; if ( count &lt; 2*connection_num ) digitalToggle(LED_RED); if ( count % 2 &amp;&amp; digitalRead(LED_RED)) digitalWrite(LED_RED, LOW); // issue #98 count++; if (count &gt;= 10) count = 0; } </code></pre> <p><a href="https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/libraries/Bluefruit52Lib/examples/Central/central_bleuart/central_bleuart.ino" rel="nofollow noreferrer">GitHub Source code</a></p> <p>I want to invoke this disconnect function, but I don't know where to get conn_handle. If anyone has any idea please help me.</p> <p>I have already tried going into libraries; the best it shows is just the definition of the callback function:</p> <pre><code>1: Bluefruit.Central.setDisconnectCallback(disconnect_callback); 2: void BLECentral::setDisconnectCallback( ble_disconnect_callback_t fp ) { _disconnect_cb = fp; } 3: class BLECentral { ... private: ble_disconnect_callback_t _disconnect_cb; } 4: typedef void (*ble_disconnect_callback_t ) (uint16_t conn_hdl, uint8_t reason); </code></pre> <p>This is all I got regarding this disconnect function in different libraries following the definition but nothing related to conn_handle.</p>
<p>Idk if its a right or not but it works.</p> <p>When there's is a new connection established, &quot;connect&quot; gets revoked, with &quot;conn_handle&quot; as its argument. If someone knows please tell how is this function revoke itself.</p> <p>But what I did is make a global variable <code>uint16_t conn_handle</code></p> <pre><code>uint16_t g_conn_handle; void connect_callback(uint16_t conn_handle) { g_conn_handle=conn_handle; // Find an available ID to use int id = findConnHandle(BLE_CONN_HANDLE_INVALID); // Eeek: Exc ... </code></pre> <p>Now I can call the Disconnect function with this <code>g_conn_handle</code> global variable.</p>
90677
|c++|
Does avr-libc have any reason to word-align C++ class member variables?
2022-09-05T18:51:12.727
<p>This sounds straightforward enough, but I'm struggling to find a good answer.</p> <p>Suppose I declare a C++ class with private members that collectively occupy an odd number of bytes. Say...</p> <pre><code>class Foo { private: uint8_t bitflags; uint32_t millis; } </code></pre> <p>or</p> <pre><code>class Foo { private: uint8_t rawData[3]; } </code></pre> <p>If I compile it using GCC or Clang (possibly, wrapped inside the Arduino IDE, or multiply-wrapped inside PlatformIO, CMake, and an IDE like CLion), is there any likely scenario where the compiler (when targeting 8-bit AVR... specifically, the ATmega2560 on an Arduino Mega2560) would be inclined to add padding bytes to the portion of the class stored in SRAM? Say... between <code>bitflags</code> and <code>millis</code>, or between an instance of <code>Foo</code> and a <code>uint64_t</code> right after it?</p> <p>If yes, what do I need to use to tell the compiler, &quot;absolutely, positively <em><strong>DO NOT</strong></em> pad variables in SRAM (and, if you find yourself in a situation where it's seemingly unavoidable, at least output a prominent compile-time warning, if not an outright compilation-stopping error)?</p> <p>Then... if I do that... are there any negative <em>consequences</em> to doing that with code that's targeting (and ultimately running upon) an 8-bit AVR?</p> <p>As far as I know, 8-bit AVR has <em>never</em> had specific opcodes for copying a <em>pair</em> of consecutive bytes between registers and SRAM (I think, because Atmel literally ran out of opcode mapping space, and had nowhere to <em>put</em> hypothetical new opcodes like, &quot;ldw rz, $f00d&quot;), and <code>movw</code> only applied to pairs of <em>registers</em>... so, in theory, there's no reason <em>for</em> the compiler to &quot;optimize&quot; SRAM access to be word-aligned.</p> <p>That said... I suppose it's not inconceivable that a compiler might <em>default</em> to word-alignment (even on platforms where it doesn't <em>matter</em>), just for the sake of ABI consistency between different platforms.</p> <p>Before someone suggests, &quot;try it and see!&quot;... I've gotten far enough into learning C++ to know that with C++, you <em><strong>can't trust</strong></em> &quot;compiles without errors and passes unit tests on <em>my computer</em>, with <em>{this} IDE</em>&quot; as a general-purpose proof-of-correctness for C++ involving &quot;implementation-defined&quot; or &quot;undefined&quot; behavior. AFAIK, padding behavior is &quot;implementation-defined&quot;.</p>
<p>GCC has an extension to add attributes to types, which you can use to tell it your alignment requirements.</p> <p>Additionally it has a <code>#pragma</code> to define the alignment, which could be used alternatively.</p> <p>But as you already suspect, for this 8-bit target there should be no reason to insert padding bytes.</p> <hr /> <p>So your question boils down to find a method to detect unwanted padding. You can do this in a standard compliant way, which I show below. Yes, it does introduce additional types, one per structure. But it does not generate any unnecessary objects that eat your precious resources.</p> <p>The &quot;trick&quot; is to use the <code>sizeof</code> operator to calculate a valid array size only, if the size of the checked type meets the expectation. If not, a compiler error safely breaks the generation of code. Granted, the error message is misleading an unsuspecting user, so it is really necessary to name the macro and the type accordingly.</p> <p>This example compiles successfully with a PC as target, but not with an AVR as target. This is intentionally to demonstrate the working, because with an AVR target the type <code>UP</code> should have no padding bytes.</p> <pre class="lang-c prettyprint-override"><code>#define ASSERT_TYPE_SIZE(Type, size) \ typedef char Assert##Type##Size[2 * (sizeof(Type) == (size)) - 1] typedef struct { char c; long l; } UP; ASSERT_TYPE_SIZE(UP, sizeof (long) + sizeof(long)); typedef struct __attribute__((packed)) { char c; long l; } P1; ASSERT_TYPE_SIZE(P1, sizeof (char) + sizeof(long)); #pragma pack(1) typedef struct { char c; long l; } P2; ASSERT_TYPE_SIZE(P2, sizeof (char) + sizeof(long)); #pragma pack() </code></pre>
90679
|softwareserial|pinmode|
Use same pin for two purposes
2022-09-05T23:44:35.590
<p>I have only one pin available and I'd need to use it both for a digitalRead and for sending serial messages (assigning it the Tx role within a SoftwareSerial). I can alternate these two operations, but I don't seem to succeed. I could be interested in other pairs as well (digitalRead+Rx, digitalWrite+Tx and digitalWrite+Rx) and I hope that understanding one will solve them all, but for now I'd be happy to get the first one working. My first naive attempt would be something like:</p> <pre><code> #include &lt;SoftwareSerial.h&gt; SoftwareSerial swSerial(7,6); int val; void setup() { pinMode(6, INPUT_PULLUP); } void loop() { val = digitalRead(6); delay(2000); swSerial.begin(19200); swSerial.print(&quot;myData&quot;); swSerial.end(); delay(2000); } </code></pre> <p>But I've made other experiments, for example with a digitalWrite, hoping that combining two forms of output would be feasible, but again no way. I know I can alternate a pin role between output and input as long as common digital read/write operations are involved, but SoftwareSerial appears to be less flexible. It seems to me it refuses to work as soon as the pin is declared/used for common digital purposes. Is there a way to accomplish my goal?</p> <p>I guess that similar requirements and fixes (make a pin role more flexible) led to the <a href="https://forum.arduino.cc/t/software-serial-with-half-duplex-for-a-shared-serial-bus/112131" rel="nofollow noreferrer">Software Serial with Half Duplex</a> library, but I'd refrain from adopting it because I feel it is overcomplicated and seems like overkill for my purpose, moreover it doesn't seem actively supported.</p> <p>To avoid a XY problem, my very initial need (I may have further ones, requiring the different pairs mentioned at the beginning) would be to check whether this pin is floating or connected to something (I can chose between Vcc or Gnd, setting up the pull-up or an external pull-down accordingly) and to send back some information (obviously this is useful if the pin is actually connected, but I have no reason not to send data anyway) alternating the tasks a few times per second at least.</p>
<p>First of all, for using the Software Serial you need to set your tx and rx pins to OUTPUT, that what the library does under the hood.</p> <p>What you may try to do is to set a millis timer (forget about delay(), never ever use it) and change pin mode to INPUT once every 200ms let's say. And after your measurements put it back to output as soon as you can.</p> <p>200ms delay is normally ok for some readings like button click. If you can read the value more rare do it (for example you may read some sensor value only once per hour). Here is an example:</p> <pre><code> #include &lt;SoftwareSerial.h&gt; SoftwareSerial swSerial(7,6); int val; byte timer = 200; // Read value every 200ms uint32_t prevTime = 0; void setup() { // Don't change pin mode here swSerial.begin(19200); } void loop() { if (millis() - prevTime &gt; timer) { // you could try swSerial.flush(); here... prevTime = millis(); // reset timer pinMode(6, INPUT_PULLUP); // changing pin mode and reading value val = digitalRead(6); pinMode(6, OUTPUT); // changing pin mode back } swSerial.print(&quot;myData&quot;); // swSerial.end(); // I don't think you need this line; } </code></pre> <p>It may be a solution from a programming point of view. But another task is to organize an electric multiplexing for 2 different devices on the same pin as was mentioned by @the busybee</p>
90688
|arduino-ide|avrdude|ide|
Provide custom AVR dude commands through the Arduino IDE
2022-09-06T15:03:45.627
<p>Besides the standard upload button that burns the code using FTDI, I want to then be able to provide custom AVRDude commands for burning fuses, when the external programmer is used.</p> <p>Is this possible to do from the IDE? Maybe if I can edit some configuration files?</p> <p>The idea is to have the IDE supply the upload command when the standard upload option is selected, but when <code>external programmer</code> is selected, i want to have custom behavior.</p> <p>The custom behavior that I want is to preserve the EEPROM and set the lock bit.</p> <p>These two actions can be performed with the following AVRDude commands:</p> <pre><code>avrdude -c usbtiny -p m328p -U hfuse:w:0xd2:m avrdude -c usbtiny -p m328p -U lock:w:0x00:m </code></pre> <p>The external programmer i use is Sparkfun's &quot;Pocket AVR Programmer&quot; which is an SPI programmer.</p> <p>So can I have custom behavior (supported by AVRDude) when I select program using external programmer?</p> <p>EDIT: I opened file <code>boards.txt</code> and i found these specifications of interest:</p> <pre><code>pro.name=Arduino Pro or Pro Mini pro.upload.tool=avrdude pro.upload.protocol=arduino pro.bootloader.tool=avrdude pro.bootloader.unlock_bits=0x3F pro.bootloader.lock_bits=0x0F pro.build.board=AVR_PRO pro.build.core=arduino pro.build.variant=eightanaloginputs </code></pre> <p>and</p> <pre><code>## Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328P ## --------------------------------------------------- pro.menu.cpu.8MHzatmega328=ATmega328P (3.3V, 8 MHz) pro.menu.cpu.8MHzatmega328.upload.maximum_size=30720 pro.menu.cpu.8MHzatmega328.upload.maximum_data_size=2048 pro.menu.cpu.8MHzatmega328.upload.speed=57600 pro.menu.cpu.8MHzatmega328.bootloader.low_fuses=0xFF pro.menu.cpu.8MHzatmega328.bootloader.high_fuses=0xDA pro.menu.cpu.8MHzatmega328.bootloader.extended_fuses=0xFD pro.menu.cpu.8MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex pro.menu.cpu.8MHzatmega328.build.mcu=atmega328p pro.menu.cpu.8MHzatmega328.build.f_cpu=8000000L </code></pre> <p>I am using Arduino Pro Mini. In the second specification, there is the option for setting the fuse bits I want. However, there is no option for the lock bits. The option for the lock bits are in the first specification - but there is no option for the fuses.</p> <p>My new questions are these:</p> <ol> <li>Should I specify the lock bits in the first specs and the fuses in the second? Will this work? I have to ask before trying anything stupid. Will the second specs &quot;inherit&quot; from the first specs?</li> <li>Will the parameters I insert here only work for the <code>Upload Using Programmer</code> option? I want the regular upload (via bootloader) to work normally.</li> <li>What happens if I ditch the Arduino platform and use a standalone AVR? If I use the same AVR that the Pro Mini platform had. Will the same settings work?</li> </ol>
<p>You can add the fuse parameters to the &quot;Upload using programmer&quot; command pattern <code>tools.avrdude.program.pattern</code> in platform.txt. Copy them from the <code>tools.avrdude.erase.pattern</code>. (The fuse values are from boards.txt)</p> <p>the modified upload command pattern:</p> <blockquote> <p>tools.avrdude.program.pattern=&quot;{cmd.path}&quot; &quot;-C{config.path}&quot; {program.verbose} {program.verify} -p{build.mcu} -c{protocol} {program.extra_params} &quot;-Uflash:w:{build.path}/{build.project_name}.hex:i&quot; -Ulock:w:{bootloader.lock_bits}:m</p> </blockquote>
90700
|json|
ArduinoJSON :: How to determine Array's size in a DOC conatinaing not only Arrays
2022-09-08T15:00:41.803
<p>Parameter file containing MQTT topics as shown below, is read into <code>StaticJsonDocument&lt;1250&gt; DOC</code> variable.</p> <p>Size of some groups may differ between MCU's, for example <code>sub_topics_win</code> may contain more topics, if MCU is 8 relay unit. For that I need the flexibility to read a specific topic that can differ in size.</p> <p>What is the rifht way to do it?</p> <pre><code>{ &quot;pub_gen_topics&quot;: [ &quot;myHome/Messages&quot;, &quot;myHome/log&quot;, &quot;myHome/debug&quot; ], &quot;pub_topics&quot;: [ &quot;myHome/Cont_A/Avail&quot;, &quot;myHome/Cont_A/State&quot; ], &quot;sub_topics&quot;: [ &quot;myHome/Cont_A&quot;, &quot;myHome/All&quot;, &quot;myHome/lockdown&quot; ], &quot;sub_topics_win&quot;: [ &quot;myHome/Windows/gFloor/TwinWindow&quot;, &quot;myHome/Windows/gFloor/Pergola&quot; ], &quot;sub_topics_SW&quot;: [ &quot;myHome/Light/int/gFloor/SalAmbient1&quot;, &quot;myHome/Light/int/gFloor/SalAmbient2&quot;, &quot;myHome/Light/int/gFloor/Lobby&quot;, &quot;myHome/Light/int/gFloor/Corridor&quot; ], &quot;sub_topics_win_g&quot;: [ &quot;myHome/Windows&quot;, &quot;myHome/Windows/gFloor&quot; ], &quot;sub_topics_SW_g&quot;: [ &quot;myHome/Light&quot;, &quot;myHome/Light/int&quot;, &quot;myHome/Light/int/gFloor/&quot; ], &quot;ver&quot;: 0.1 } </code></pre>
<p>If your question is <em>How can I read each element of an array when I don't know its size?</em>, then simply use a for-loop, like so:</p> <pre class="lang-cpp prettyprint-override"><code>JsonArray sub_topics_win = doc[&quot;sub_topics_win&quot;]; for (const char* topic : pub_gen_topics) { Serial.println(topic); } </code></pre> <p>See also: <a href="https://arduinojson.org/v6/api/jsonarray/begin_end/" rel="nofollow noreferrer">JsonArray::begin() / end()</a>, <a href="https://arduinojson.org/v6/api/jsonarray/size/" rel="nofollow noreferrer">JsonArray::size()</a>.</p>
90710
|attiny85|
ATTiny84 I2C with NeoPixels not working
2022-09-09T13:51:01.720
<p>I fetch RGB values via I2C - which works (with a splitting function).</p> <p>Now I have a problem:</p> <ul> <li>When I write values directly into strip.color() like strip.Color(255,0,0,0) the NeoPixels turn red when receiving the values.</li> <li>When I use the values from the I2C connection it won't work anymore. But the values are correct if I have a look in the Serial Monitor.</li> </ul> <p>Maybe the data type is wrong or something?</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_NeoPixel.h&gt; #define LED_PIN 4 #define LED_COUNT 4 static const int SLAVE_ADDRESS = 0x08; uint32_t currentColor; int currentBrightness = 50; int flashState = 0; String ledRed, ledGreen, ledBlue, ledWhite; String temp; String payload; Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRBW + NEO_KHZ800); void setup() { Serial.begin(9600); strip.begin(); strip.show(); // Turn off all pixels asap strip.setBrightness(50); // Set brightness pinMode(3, OUTPUT); digitalWrite(3, HIGH); Wire.begin(SLAVE_ADDRESS); Wire.onReceive(change); } // Set all pixels to color void setPixelColors(uint32_t color) { for(int p = 0; p &lt; LED_COUNT; p++) { strip.setPixelColor(p, color); } strip.show(); delay(1000); digitalWrite(3, HIGH); } // Split the I2C message String split(String s, char parser, int index) { String rs=&quot;&quot;; int parserIndex = index; int parserCnt=0; int rFromIndex=0, rToIndex=-1; while (index &gt;= parserCnt) { rFromIndex = rToIndex+1; rToIndex = s.indexOf(parser,rFromIndex); if (index == parserCnt) { if (rToIndex == 0 || rToIndex == -1) return &quot;&quot;; return s.substring(rFromIndex,rToIndex); } else parserCnt++; } return rs; } void loop() { // ... } void change(int howMany) { digitalWrite(3, LOW); temp = &quot;&quot;; if (Wire.available()) { // Fetch the string while(Wire.available()) { char c = Wire.read(); temp.concat(c); } payload = String(temp); flashState = split(payload, ',', 0).toInt(); ledRed = split(payload, ',', 1); ledGreen = split(payload, ',', 2); ledBlue = split(payload, ',', 3); ledWhite = split(payload, ',', 4); byte bufRed[3]; ledRed.toCharArray(bufRed, 3); byte bufGreen[3]; ledGreen.toCharArray(bufGreen, 3); byte bufBlue[3]; ledBlue.toCharArray(bufBlue, 3); byte bufWhite[3]; ledWhite.toCharArray(bufWhite, 3); //setPixelColors(strip.Color(255, 0, 255, 0)); // WORKING currentColor = strip.Color(bufRed, bufGreen, bufBlue, bufWhite); setPixelColors(currentColor); // NOT WORKING } // Proof the I2C reading is finished delay(10); } </code></pre> <p>I tried different data types, attached a status LED so I know it the I2C connection is working. When I test it with my UNO I get for R=255 G=0 B=255 W=0; like intended.</p> <p>&quot;Fun fact&quot;: On my UNO it works like a charm. It's just the ATTiny85 that won't accept that values(?)</p> <hr /> <p>New Code:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_NeoPixel.h&gt; #define LED_PIN 4 #define LED_COUNT 20 static const int SLAVE_ADDRESS = 0x08; int currentBrightness = 50; int flashState = 0; int ledRed, ledGreen, ledBlue, ledWhite; volatile bool recvFlag = false; volatile uint32_t currentColor = 0; String temp; String payload; Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRBW + NEO_KHZ800); void setup() { Serial.begin(9600); strip.begin(); strip.show(); // Turn OFF all pixels ASAP strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255) Wire.begin(SLAVE_ADDRESS); Wire.onReceive(change); } void setPixelColors(uint32_t color) { for (int p = 0; p &lt; LED_COUNT; p++) { strip.setPixelColor(p, color); strip.show(); } } String split(String s, char parser, int index) { String rs = &quot;&quot;; int parserIndex = index; int parserCnt = 0; int rFromIndex = 0, rToIndex = -1; while (index &gt;= parserCnt) { rFromIndex = rToIndex + 1; rToIndex = s.indexOf(parser, rFromIndex); if (index == parserCnt) { if (rToIndex == 0 || rToIndex == -1) return &quot;&quot;; return s.substring(rFromIndex, rToIndex); } else parserCnt++; } return rs; } void loop() { if (recvFlag) { payload = String(temp); flashState = split(payload, ',', 0).toInt(); ledRed = split(payload, ',', 1).toInt(); ledGreen = split(payload, ',', 2).toInt(); ledBlue = split(payload, ',', 3).toInt(); ledWhite = split(payload, ',', 4).toInt(); currentColor = strip.Color(ledRed, ledGreen, ledBlue, ledWhite); setPixelColors(currentColor); recvFlag = false; } } void change(int howMany) { temp = &quot;&quot;; if (Wire.available()) { // Fetch the string while (Wire.available()) { char c = Wire.read(); temp.concat(c); } // Proof the I2C reading is finished recvFlag = true; } } </code></pre>
<p>Honestly I don't know, why exactly this works on your Uno. You need to know, that the <code>onReceive</code> callback function is called from an ISR (Interrupt Service Routine). And inside an ISR you cannot do things, that rely on interrupts to work (like <code>delay()</code>), since only one interrupt can run at a time. I'm not sure, how the Neopixel library works in its core, but its probably not a good idea to run the <code>show()</code> method inside an ISR. Also generally you don't want to do long things inside an ISR, since it will block all the other interrupt powered functions of your microcontroller (for example I2C, Serial, time keeping via <code>delay()</code> or <code>millis()</code>...).</p> <p>Instead the best practice is to only set a flag and then do these things in the main code (aka in <code>loop()</code>). So something like this:</p> <pre><code>volatile bool recv_flag = false; volatile uint32_t current_color = 0; void setup(){ // Initiating everything like you already did in your code ... } void loop(){ if(recv_flag){ setPixelColors(currentColor); recv_flag = false; } } void change(int howMany) { digitalWrite(3, LOW); temp = &quot;&quot;; if (Wire.available()) { // Doing all the data parsing like you already did ... // save current color in global variable currentColor = strip.Color(bufRed, bufGreen, bufBlue, bufWhite); // set flag recv_flag = true; } } </code></pre> <p>Note that every variable, that will be written to inside an ISR should be declared as <code>volatile</code>. This prevents the compiler from optimizing it out, since it cannot know when the interrupts will happen. So it might think that this variable will never change and just replace it with a literal. The <code>volatile</code> keyword prevents that.</p> <hr /> <p>As mentioned above I'm even wondering, why your code works on the Uno. Though the main difference between the Uno and the Attiny84 is, that the Uno as a full fledged I2C hardware interface, while the Attiny84 only has an USI (Universal Serial interface). So the Uno has most of the I2C communication implemented in hardware, while the Attiny84 needs to run (probably interrupt based) code to do the communication.</p>
90729
|usb|
Rename cu.usbserial-1410 on macOS
2022-09-12T09:18:06.280
<p>Is it possible to rename, e.g., <a href="https://stackoverflow.com/questions/8632586/macos-whats-the-difference-between-dev-tty-and-dev-cu">cu.usbserial-1410</a> to something else?</p> <p>I have to connect multiple Arduino's and right now the order is rather important. Being able to set a fixed name would help a lot.</p>
<h3>Proposal:</h3> <p>Instead of trying to convince the PC's OS (be it macOS, Windows, or Linux) to use a fixed name for interfaces that connect specific Arduinos, add a identifying feature to your Arduino application. Then from the PC application ask each connected Arduino for its name to identify it.</p>
90743
|c++|
Can't convert string to UTF-16LE for MD5 calculation on an Arduino
2022-09-14T11:38:26.383
<h2>TLDR</h2> <p>I need to convert text from a website into UTF-16LE format so that I can get the proper MD5 checksum but can't figure out how to go about doing that. This is all happening on an Arduino to log in to a router.</p> <h2>Background</h2> <p>I want to read values from a smart home device connected to a Fritz!Box router using an Arduino with an ethernet connection. The router has an open <a href="https://avm.de/service/schnittstellen/" rel="nofollow noreferrer">API</a> and I'm using HTTP (<a href="https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/AVM_Technical_Note_-_Session_ID_english_2021-05-03.pdf" rel="nofollow noreferrer">EN</a>|<a href="https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/AVM_Technical_Note_-_Session_ID_deutsch_2021-05-03.pdf" rel="nofollow noreferrer">DE</a>) to get the values. C++ programming is not my strong point.</p> <p>I have been basing my attempts on <a href="https://raspberrypiandstuff.wordpress.com/2017/08/03/reading-the-temperature-from-fritzdect-devices/" rel="nofollow noreferrer">BASH</a> and <a href="https://github.com/andig/fritzapi/blob/master/index.js" rel="nofollow noreferrer">javascript</a> examples. For MD5 calculation I'm using tzikis' <a href="https://github.com/tzikis/ArduinoMD5" rel="nofollow noreferrer">ArduinoMD5 library</a>.</p> <h2>Steps</h2> <p>Based on the manual, you need to do the following:</p> <ol> <li>Contact the router to get a challenge string (router sends XML)</li> <li>Generate a response by calculating an MD5 checksum using the challenge string and password: <code>&lt;challenge&gt;-&lt;password&gt;</code></li> <li>Send the response, <code>&lt;challenge&gt;-&lt;response&gt;</code>, via POST</li> <li>Receive the XLM answer from the router containing the SID</li> <li>Use SID to request data or control a smart home device</li> </ol> <p>I'm stuck on step 2. I have the challenge but cannot calculate the correct checksum.</p> <p>The manual states:</p> <blockquote> <p>The MD5 hash is generated from the byte sequence of the UTF-16LE coding of this string (without BOM and without terminating 0 bytes).</p> </blockquote> <h2>Attempts</h2> <p>So far I can request the challenge: 70067288 for example. The reponse appears to always be alphanumeric. My password is also alphanumeric.</p> <pre class="lang-cpp prettyprint-override"><code>unsigned char* hash2 = MD5::make_hash(&quot;1234567z-äbc&quot;); char *md5str2 = MD5::make_digest(hash2, 16); free(hash2); Serial.print(&quot;MD5: &quot;); Serial.println(md5str2); </code></pre> <p>This was my attempt at confirmation. The manual gave <code>1234567z</code> as a challenge example with <code>äbc</code> (the a in the example does indeed have umlauts) as a password. The response shown for this example was <code>1234567z-9e224a41eeefa284df7bb0f26c2913e2</code> but my checksum from the above code was <code>935fe44e659beb5a3bb7a4564fba0513</code>.</p> <p>I tried &quot;manually&quot; generating UTF-16LE and calculating the MD5 but that didn't work either.</p> <pre class="lang-cpp prettyprint-override"><code>byte rawTest[] = {0x3100, 0x3200, 0x3300, 0x3400, 0x3500, 0x3600, 0x3700, 0x7a00, 0x2d00, 0xe400, 0x6200, 0x6300}; char buffer[12] = {}; unsigned char* hash2 = MD5::make_hash(&amp;buffer[0]); char *md5str2 = MD5::make_digest(hash2, 16); free(hash2); Serial.print(&quot;MD5: &quot;); Serial.println(md5str2); </code></pre> <p>It gave me <code>d41d8cd98f00b204e9800998ecf8427e</code>.</p> <p>I am not entirely sure the example given was correctly calculated. Using their example in the API documentation with BASH code from the site mentioned above, I get a different answer: <code>1234567z-bb6e5b7c7d4d485590f4e084ad3da989</code>.</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash # ----------- # definitions # ----------- FBF=&quot;http://192.168.178.1/&quot; USER=&quot;root&quot; PASS=&quot;äbc&quot; AIN=&quot;AINOFYOURFRITZDECTDEVICE&quot; # --------------- # fetch challenge # --------------- CHALLENGE=&quot;1234567z&quot; # ----- # login # ----- MD5=$(echo -n ${CHALLENGE}&quot;-&quot;${PASS} | iconv -f ISO8859-1 -t UTF-16LE | md5sum -b | awk '{print substr($0,1,32)}') RESPONSE=&quot;${CHALLENGE}-${MD5}&quot; echo $RESPONSE </code></pre> <p>Any help getting it working is greatly appreciatet.</p> <hr /> <h2>Working Example (with caveats)</h2> <p>Requirements:</p> <ul> <li>Password using only characters found in ASCII</li> <li>Password at least 17 characters long</li> </ul> <p>The password must use <em>only</em> ASCII characters due to the simple way it's being converted to UTF-16LE.</p> <p>I can't explain why the password must be at least 17 characters long though. My code checks the length of the actual password programmatically.</p> <p>With a password at least 17 characters long I get something like this:</p> <blockquote> <p>Challenge: 6c607ee5</p> <p>Challenge Pass (26): 6c607ee5-01234567890123456</p> <p>Challenge Pass Preallocation Length: 26</p> <p>MD5 (UTF-16LE): 3b26241ae4aab8eaf71d5c1599932178</p> </blockquote> <p>Any password short and I get something like this:</p> <blockquote> <p>Challenge: 621611e1</p> <p>Challenge Pass (26): 621611e1-0123456789012345�</p> <p>Challenge Pass Preallocation Length: 25</p> <p>MD5 (UTF-16LE): 30a163ab8a267adfbb524b2b7412e81b</p> </blockquote> <p>Please excuse any poor coding, C++ is not my strongpoint.</p> <pre class="lang-cpp prettyprint-override"><code>void fritzboxSID() { EthernetClient fritzBox; const char* pass = &quot;01234567890123456&quot;; // 17 ASCII character minimum const char* user = &quot;fritz3456&quot;; // Account on router, randomly generated or user created const size_t passLength = strlen(pass); // Password length char c; uint8_t xml = 0; char challenge[9] = {0}; // Challenge char challengePass[8 + 1 + passLength]; // challenge-password uint8_t challengeCount = 0; if (fritzBox.connect(&quot;192.168.200.1&quot;, 80)) { // Send login request fritzBox.println(&quot;GET /login_sid.lua HTTP/1.1&quot;); fritzBox.println(&quot;Host: 192.168.200.1&quot;); fritzBox.println(&quot;Connection: close&quot;); fritzBox.println(); while (fritzBox.connected()) { while (fritzBox.available()) { c = fritzBox.read(); // Read a single character from the router response if (c == '&gt;') { xml++; } if (xml == 5) { // Challenge starts after the fifth &gt; if (challengeCount &gt; 0 &amp; challengeCount &lt; 9) { // Save the challenge, character by character challenge[challengeCount-1] = c; challengePass[challengeCount-1] = c; } challengeCount++; } Serial.print(c); // Print HTTP response } } challengePass[8] = '-'; for (size_t i = 0;i &lt; passLength; i++){ // Copy password into the combined challenge-password string challengePass[i+9] = pass[i]; } // Show challenge and pass, checking lengths // If the strlen(challengePass) doesn't equal the preallocation length then the MD5 will be incorrect Serial.println(&quot;&quot;); Serial.print(&quot;Challenge: &quot;); Serial.println(challenge); Serial.print(&quot;Challenge Pass (&quot;); Serial.print(strlen(challengePass)); Serial.print(&quot;): &quot;); Serial.println(challengePass); Serial.print(&quot;Challenge Pass Preallocation Length: &quot;); Serial.println(8 + 1 + passLength); // Convert to UTF-16LE (only works for standard ASCII characters) const size_t length = strlen(challengePass); char buffer[2*length]; for (size_t i = 0; i &lt; length; i++) { buffer[2*i] = challengePass[i]; buffer[2*i+1] = 0; } // Generate MD5 unsigned char* hash = MD5::make_hash(buffer, 2*length); char *md5str = MD5::make_digest(hash, 16); free(hash); Serial.print(&quot;MD5 (UTF-16LE): &quot;); Serial.println(md5str); } else { Serial.println(&quot;Cannot connect to 192.168.200.1&quot;); } } </code></pre> <p>If it helps, the response from the router for the initial login request is this:</p> <pre><code>HTTP/1.1 200 OK Cache-Control: no-cache Connection: close Content-Type: text/xml Date: Fri, 16 Sep 2022 08:21:27 GMT Expires: -1 Pragma: no-cache X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff Content-Security-Policy: default-src 'none'; connect-src 'self'; font-src 'self'; frame-src https://service.avm.de https://help.avm.de https://www.avm.de https://avm.de https://assets.avm.de https://clickonce.avm.de http://clickonce.avm.de http://download.avm.de https://download.avm.de 'self'; img-src 'self' https://tv.avm.de https://help.avm.de/images/ http://help.avm.de/images/ data:; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; media-src 'self' &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&lt;SessionInfo&gt;&lt;SID&gt;0000000000000000&lt;/SID&gt;&lt;Challenge&gt;621611e1&lt;/Challenge&gt;&lt;BlockTime&gt;0&lt;/BlockTime&gt;&lt;Rights&gt;&lt;/Rights&gt;&lt;Users&gt;&lt;User last=&quot;1&quot;&gt;fritz3456&lt;/User&gt;&lt;User&gt;UserName&lt;/User&gt;&lt;/Users&gt;&lt;/SessionInfo&gt; </code></pre>
<p>You have to convert the string &quot;&lt;challenge&gt;-&lt;password&gt;&quot; to UTF-16LE. If the whole string is plain ASCII, the conversion is trivial: you just have to add a zero byte after each ASCII byte.</p> <pre class="lang-cpp prettyprint-override"><code>// ASCII string to be hashed. const char* text = &quot;1234567z-abc&quot;; // umlaut removed // Convert to UTF-16LE. const size_t length = strlen(text); char buffer[2*length]; for (size_t i = 0; i &lt; length; i++) { buffer[2*i] = text[i]; buffer[2*i+1] = 0; } // Compute and print the hash. unsigned char* hash2 = MD5::make_hash(buffer, 2*length); char *md5str2 = MD5::make_digest(hash2, 16); free(hash2); Serial.print(&quot;MD5: &quot;); Serial.println(md5str2); </code></pre> <p>Note that I use the two-parameter version of <code>MD5::make_hash()</code> in order to pass the length of the buffer. The one parameter version of this method would stop at the first zero byte.</p> <hr /> <p><strong>Edit</strong>: Regarding your extended question (the new section “Working Example”), this is a problem completely unrelated to the previous one. It is about string termination.</p> <p>In C and C++, strings are arrays of characters terminated with a NUL ASCII character (numeric value zero). The terminating NUL is not part of the string per se, but it should be stored in the array holding the string. String literals are interpreted by the compiler as NUL-terminated arrays of characters. Every function that expects a string as an input expects it to be NUL-terminated.</p> <p>In this particular instance, you failed to NUL-terminate <code>challengePass</code>. When this array is given to <code>strelen()</code>, this function scans the memory until it finds a zero byte. If that zero byte happens to be right after the end of the array, your code will work as expected. Otherwise, any non-zero byte coming after <code>challengePass</code> in memory will be interpreted as being part of the string. The program behavior is unpredictable, because you do not know what will be stored in memory right after <code>challengePass</code>.</p> <p>The solution is to NUL-terminate the string. Start by allocating one more byte:</p> <pre class="lang-cpp prettyprint-override"><code>char challengePass[8 + 1 + passLength + 1]; // challenge-password </code></pre> <p>Then, right after copying the password, add a zero byte to terminate the string:</p> <pre class="lang-cpp prettyprint-override"><code>challengePass[8 + 1 + passLength] = '\0'; // terminate the string </code></pre> <p>Note that <code>'\0'</code> means “the character with numeric value zero”.</p> <p>Alternatively, you can terminate the string right after adding the dash, then use <code>strcat()</code> to concatenate the password. <code>strcat()</code> will take care of terminating the string:</p> <pre class="lang-cpp prettyprint-override"><code>challengePass[8] = '-'; challengePass[9] = '\0'; // temporarily terminate the string strcat(challengePass, pass); // append password </code></pre>
90752
|arduino-nano|analogread|analogwrite|
IF statement to run even if the requirement isn't met anymore
2022-09-15T14:32:24.087
<p>I have built a flasher for the headlamps on my race car. Whilst it works when I hold the switch down, if I release the switch and the circuit is closed my IF statements requirements are no longer met and it stops flashing.</p> <p>Is there a way to have it continue to run the IF statement (but only once) even after I've let go of the switch and the requirement is no longer met?</p> <p>Thanks in advance.</p> <p>CODE:</p> <pre><code>#define trig A3 const int flash = 3; //D3 const float mVc = 4.67; //reference voltage float counts = 0; float mV = 0; void setup() { Serial.begin(115200); pinMode(flash, OUTPUT); } void loop() { counts = analogRead(trig); //counts = 255; Serial.println(String(counts)); mV = (counts*mVc) / 1000; Serial.println(&quot;Input Voltage: &quot; + String(mV) + &quot;v&quot;); //delay(1000); // voltage will need to be changed to matched output voltage when on car if (counts &gt; 10) { analogWrite(flash, 100); delay(300); analogWrite(flash, 0); delay(80); analogWrite(flash, 100); delay(300); analogWrite(flash, 0); delay(80); analogWrite(flash, 100); delay(300); analogWrite(flash, 0); delay(80); analogWrite(flash, 100); delay(300); analogWrite(flash, 0); delay(80); analogWrite(flash, 100); delay(300); analogWrite(flash, 0); delay(1000); } } </code></pre> <hr /> <p>EDIT:</p> <p>TL;DR Don't use voltage dividers to power the Nano.</p> <p>When using a voltage divider to power the Nano (I know, I know) the below solution didn't fix the issue. I thought it may be due to the voltage dropping when the Nano supplies the 5vo to the mosfet but I'm not sure why holding the switch would stop that from happening. Regardless I swapped to a linear voltage regulator and then it started to flash, <em>&quot;Hurrah!&quot;</em> -- almost.</p> <p>With the regulator in it was running the code constantly. I decided to print the runcount and I got a number over 35,000, meaning it would run the flash 5 times for &gt;35,000 times. Although curious as to what would happen when it reached zero, I decided to go back to my original code and...now it works.</p> <p>So I guess the lesson is: Even if you can calculate the drop off, don't run your Nano on a voltage divider.</p> <hr /> <p><strong>I have checked the answer below as the solution, although it didn't fix my issue there is no reason it shouldn't have worked and it may be useful to someone else.</strong></p>
<p>You could define an <code>int runcount = 0</code> variable at the top. Then change your loop logic to something like</p> <pre><code>if (counts &gt; 10) { runcount = 2; } if (runcount-- &gt; 0) { //flashy flashy } </code></pre> <p>The effect is, that while button is pressed and <code>counts &gt; 10</code>, runcount is set to two. Every time we check the runcount, it is decreased by 1. While the button is pressed, runcount is resat to 2. If you let go of the button, runcount will be 1 at the start of the if condition check. It will be compared to 0, condition will be true, and it will then be decreased to 0 and the if section will be executed one last time. Using another number than 2 will change the number of extra runs.</p>
90756
|arduino-nano|bluetooth|android|
Robot car not working
2022-09-15T15:07:47.387
<p>My robot car won’t respond to my command. The code below worked before however, this time there is no response. I’ve tried experimenting with the code in the first while loop. I’ve tried different code from other projects similar to this. I’ve played with the schematics however, nothing seems to work.</p> <p>This is my code:</p> <pre><code>#include &lt;SoftwareSerial.h&gt; // TX RX software library for bluetooth #include &lt;Servo.h&gt; // servo library Servo myservo1, myservo2, myservo3; // servo name int bluetoothTx = 10; // bluetooth tx to 10 pin int bluetoothRx = 11; // bluetooth rx to 11 pin int motorOne = 4; int motorOne2 = 5; int motorTwo = 6; int motorTwo2 = 7; int enA = 3; int enB = 2; SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); //initial motors pin char command; char Value; void setup() { myservo1.attach(2); // attach servo signal wire to pin 9 myservo2.attach(8); myservo3.attach(12); //Setup usb serial connection to computer Serial.begin(9600); //Setup Bluetooth serial connection to android bluetooth.begin(9600); } void loop() { while (bluetooth.available() &gt; 2) { Value = bluetooth.read(); Serial.println(Value); } if ( Value == 'F') { // Robo Pet Run Forward digitalWrite(enA, 255); digitalWrite(enB, 255); digitalWrite(motorOne, HIGH); digitalWrite(motorOne2, LOW); digitalWrite(motorTwo, HIGH); digitalWrite(motorTwo2, LOW); } else if (Value == 'B') { //Robo Pet Run Backward digitalWrite(enA, 255); digitalWrite(enB, 255); digitalWrite(motorOne, LOW); digitalWrite(motorOne2, HIGH); digitalWrite(motorTwo, LOW); digitalWrite(motorTwo2, HIGH); } else if (Value == 'L') { //Robo Pet Turn Left digitalWrite(enA, 255); digitalWrite(motorOne, LOW); digitalWrite(motorOne2, LOW); digitalWrite(motorTwo, HIGH); digitalWrite(motorTwo2, LOW); } else if (Value == 'R') { //Robo Pet Turn Right digitalWrite(enB, 255); digitalWrite(motorOne, HIGH); digitalWrite(motorOne2, LOW); digitalWrite(motorTwo, LOW); digitalWrite(motorTwo2, LOW); } else if (Value == 'S') { //Robo Pet Stop digitalWrite(motorOne, LOW); digitalWrite(motorOne2, LOW); digitalWrite(motorTwo, LOW); digitalWrite(motorTwo2, LOW); } //Read from bluetooth and write to usb serial if(bluetooth.available()&gt;= 2 ) { unsigned int servopos = bluetooth.read(); unsigned int servopos1 = bluetooth.read(); unsigned int realservo = (servopos1 *256) + servopos; Serial.println(realservo); if (realservo &gt;= 1000 &amp;&amp; realservo &lt;1180) { int servo1 = realservo; servo1 = map(servo1, 1000, 1180, 0, 180); myservo1.write(servo1); Serial.println(&quot;Servo 1 ON&quot;); delay(10); } if (realservo &gt;= 2000 &amp;&amp; realservo &lt;2180) { int servo2 = realservo; servo2 = map(servo2, 2000, 2180, 0, 180); myservo2.write(servo2); Serial.println(&quot;Servo 2 ON&quot;); delay(10); } if (realservo &gt;= 3000 &amp;&amp; realservo &lt;3180) { int servo3 = realservo; servo3 = map(servo3, 3000, 3180, 0, 180); myservo3.write(servo3); Serial.println(&quot;Servo 3 ON&quot;); delay(10); } } } </code></pre> <p>I’m using this app: <a href="https://play.google.com/store/apps/details?id=com.giumig.apps.bluetoothserialmonitor&amp;hl=en&amp;gl=US" rel="nofollow noreferrer">https://play.google.com/store/apps/details?id=com.giumig.apps.bluetoothserialmonitor&amp;hl=en&amp;gl=US</a></p> <p>And here are the schematics: <a href="https://i.stack.imgur.com/IToLw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IToLw.png" alt="schematic" /></a></p>
<p>@timemage</p> <p>Your answer was part of the solution!</p> <p>Thank you very much! In the first while loop I switched it from <code>bluetooth.available &gt; 2</code> to <code>bluetooth.available &gt; 0</code> and then switched the signs of the TX and RX. Now the robot car is responding and running. However it won't turn left even though both motors work fine.</p>
90758
|attiny|
On ATtiny84, why does delay() stop working properly when RadioHead ASK is used?
2022-09-15T16:07:37.160
<p>When I call the <code>delay()</code> function on the ATtiny84 micro, it delays for the expected time, until I call the <code>init()</code> function on an <code>RH_ASK</code> object. After this, the micro seems to freeze.</p> <pre><code>#include &lt;RH_ASK.h&gt; RH_ASK driver(); void setup() { delay(100); // works ok driver.init(); delay(100); // freezes a long time (or maybe forever?) } </code></pre>
<p>After reading the source code, <code>RH_ASK.cpp</code>, I found a commented out macro.</p> <pre><code>// RH_ASK on ATtiny8x uses Timer 0 to generate interrupts 8 times per // bit interval. Timer 0 is used by Arduino platform for millis()/micros() // which is used by delay() // Uncomment the define RH_ASK_ATTINY_USE_TIMER1 bellow, if you want to use // Timer 1 instead of Timer 0 on ATtiny // Timer 1 is also used by some other libraries, e.g. Servo. Alway check // usage of Timer 1 before enabling this. // Should be moved to header file //#define RH_ASK_ATTINY_USE_TIMER1 </code></pre> <p>In other words, the default behaviour of RadioHead ASK <code>init()</code> is to use <strong>Timer 0</strong>, which causes <code>delay()</code> (which uses <code>millis()</code>/<code>micro()</code>) to behave incorrectly.</p> <p><strong>To fix:</strong> Tell RadioHead ASK to use <strong>Timer 1</strong>. Because the <code>RH_ASK_ATTINY_USE_TIMER1</code> macro is in the source and not the header (for now), you have to modify the actual RadioHead ASK source file, <code>RH_ASK.cpp</code>*. Un-comment the line <code>#define RH_ASK_ATTINY_USE_TIMER1</code> which will use <strong>Timer 1</strong> instead of <strong>Timer 0</strong>. Re-compile your code, and <code>delay()</code> should start working properly again.</p> <p>* <code>RH_ASK.cpp</code> can be found in <code>%USERPROFILE%\Documents\Arduino\libraries\RadioHead</code> on Windows, if you installed RadioHead via the Arduino IDE library manager.</p>
90765
|arduino-nano|led|
Strange problems driving an Optocoupler (PC123) with a Nano
2022-09-17T04:03:44.877
<p>I'm having some strange issues getting a Nano to drive a PC123 optocoupler properly.</p> <p>What I'm trying to do: In the real world, I need to press a button ONCE, and have the device that I'm connecting this too, see FIVE quick button presses... (Input 1 press, and Output 5 presses, at the timing I set in the code). I am using a mix of LED &quot;Blinking / Flashing&quot; code to do what I need.</p> <p>My connection of the Opto seems fine. It works perfectly if I run this &quot;BLINK&quot; code: (With the PC123 optocoupler connected to Pin13):</p> <pre class="lang-cpp prettyprint-override"><code>// the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(200); // wait for a while digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(200); // wait for a while } </code></pre> <p>When I run this, the Optocoupler turns ON and OFF as I need, and the device I am controlling is happy, but it obviously runs forever as I have no counters or anything.. (This proves my hardware is good at this point!)</p> <p>But, when I try this following code, with the exact same hardware circuit, the output goes HIGH as soon as I ground Pin2, and it stays HIGH! It holds the optocoupler ON and there is no ON/OFF or &quot;blinking or flashing&quot;. BUT, it only does this when the OPTO is connected (there is load) on the Nano output. If I disconnect the Opto, the Pin13 LED will flash as expected. And my code seems to work fine (on the on-board Pin 13 LED).</p> <p>VERY interestingly and very strangley though, when the &quot;power-up&quot; Pin 13 LED flashes (i.e- when you power cycle the Nano, or press the reset button) this will trigger the Opto ON/OFF perfectly! But when the code starts to run, via my Pin 2 input switch, with the Opto connected to the Nano, the output locks HIGH again! What the!?</p> <pre class="lang-cpp prettyprint-override"><code>int ledPin = 13; // LED is connected to digital pin 13 int switchPin = 2; // switch connected to digital pin 2 int switchValue; // a variable to keep track of when switch is pressed int counter = 0; void setup() { pinMode(ledPin, OUTPUT); // sets the ledPin to be an output pinMode(switchPin, INPUT); // sets the switchPin to be an input digitalWrite(switchPin, HIGH); // sets the default (unpressed) state of switchPin to HIGH } void loop() // run over and over again { switchValue = digitalRead(switchPin); // check to see if the switch is pressed if ((switchValue == LOW) &amp;&amp; (counter &lt;= 1)) { // if the switch is pressed then, for(int ii = 0; ii &lt;= 5; ii++) // 7 = 4 flashes, 5 = 3 flashes, etc { digitalWrite(ledPin, !digitalRead(ledPin)); delay(100); // Length of the flashes in ms counter++; } } if (switchValue == HIGH) //if ((switchValue == HIGH) &amp;&amp; (counter &gt; 2)) { counter = 0; delay(100); // Debounce } } </code></pre> <p>I have tried filtering capacitors, diodes, resistance, pull-ups, pull-downs, everything I can think of and I am at a loss. Can anyone help me out? I'm thinking its a code issue (because I am an Arduino noob - please be gentle!), or a maybe a deficiency in the hardware of the Nano? FYI, I have done all of this on different Input and Output pins with the same results.</p> <p>Any help would be greatly appreciated!</p>
<p><strong>Thank you @DrG</strong> for your excellent reply! I really appreciate the time you have taken on this. I will answer your questions here:</p> <ul> <li><p>What am I trying to do? I am adding the Nano to a Ham Radio Transceiver, that can change frequency (via button presses on the microphone) in only 1kHz, or 10kHz frequency steps. What I am doing here, is by adding this Nano to the microphone button circuit, and selecting the &quot;1kKz&quot; step option, I will get a &quot;5kHz&quot; step! This is great for searching for SSB signals quicky (1kHz is slow, 10kHz is too big and you miss some!). So, I press 1 time, the radio will step 5 times. This is the purpose of my project. :)</p> </li> <li><p>How have I wired it up? <strong>Exactly</strong> the same as you have shown, and I have also used both D13 (not recommended as you said, and D10 (as you have used in your proposed answer).</p> </li> <li><p>Your code is great, and I really like that it will use D13 to show what it's doing on the LED, and use D10 to drive the Opto. GREAT!</p> </li> </ul> <p>Now - here is the crazy part... Even with your code, and the exact circuit (other than my PC123 vs your 4N25 (I have 4N35's here too), I get exactly the same problem I had before! As soon as the Nano drives the Opto, regardless of the GPIO I configure, it locks HIGH! The D13 LED flashes as expected, but D10 goes high and never goes low again, until a reboot or power cycle...</p> <p>I now believe that even my original code is fine (not the best way to do it, but still functional) but my NANO is faulty! It's an &quot;ELEGOO NANO&quot; clone. And I think it's the issue!!!</p> <p>Your input is not wasted as I will use your code, it is much better than mine! :) I am going to get a new NANO and try this again, and now I am pretty confident that with a new Arduino, this will work! I will report back and let you know how it goes.</p> <p>Best regards,</p> <p>Pez</p>
90766
|testing|platformio|
Simulate pin behaviour based on PulseView recording
2022-09-17T11:35:29.200
<p>I have a bunch of PulseView recordings from an existing device. Currently to verify if my Arduino handles the input properly I always use the real device. However it would be great if I could somehow test my code with existing recordings. I am using platform.io. Perhaps there is some test framework that can mock a pin based on a recording? For example when I start the test, pin 8 should be high for 10μs then low for 7 and so on. Is there some framework to mock such things?</p>
<p>I've never heard of such a test framework and I doubt there is one, at least for hobbyists. Such a framework would need to include a lot of hardware to accommodate all the possible electrical test cases and also a rather complex software to control the hardware according to user input. So it is not really practical to have a general testing framework.</p> <p>But you can build your own for your specific case. Using another Arduino and outputting the requested pulses should not be too difficult. In the simplest version just some <code>digitalWrite()</code>s and some <code>delayMicroseconds()</code> calls.</p>
90775
|arduino-uno|esp8266|max7219|
Removing spaces between characters in MD_Parola
2022-09-18T06:13:57.003
<p>I'm using ESP8266 and Max7219 module (8*32) and <a href="https://github.com/MajicDesigns/MD_Parola" rel="nofollow noreferrer">MD_Parola library</a>. To create my own font, at first I used of <a href="https://pjrp.github.io/MDParolaFontEditor" rel="nofollow noreferrer">MDParolaFontEditor</a> and created the following fonts.</p> <p><a href="https://i.stack.imgur.com/JXRHF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JXRHF.png" alt="enter image description here" /></a></p> <p>I edited file MD_MAX72xx_font.cpp using Arduino IDE and saved them as 150 and 151. I want to have the output as the following.</p> <p><a href="https://i.stack.imgur.com/GxMZg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GxMZg.png" alt="enter image description here" /></a></p> <p>But, the output is as:</p> <p><a href="https://i.stack.imgur.com/G3Rso.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G3Rso.png" alt="enter image description here" /></a></p> <p>As you can see, there is a space between them! I think this space is automatically added between characters. My problem is that, how can I remove this space?</p> <p>My code:</p> <pre><code>void loop () { char MyText[]={151,150,0}; P.displayText(MyText, PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT); P.displayAnimate(); delay(3000); } </code></pre>
<p>The matrix with the extra space is 9 (not 8) columns wide (possibly because is was designed to be able to display a colon on a clock).</p>
90796
|arduino-ide|uart|class|ble|nrf52|
How does a callback function get revoke itself eg. Connect function get revoked when there is new connection
2022-09-20T11:03:40.327
<p>Further to my previous question <a href="https://arduino.stackexchange.com/questions/90671/nrf52832-ble-conn-handle-to-disconnect-the-current-connected-devices">here</a></p> <p>Can anyone help me understand how the callback function gets revoked itself? The connect function, disconnect function.</p> <p>BLE custom UUID code source <a href="https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/custom-central-hrm" rel="nofollow noreferrer">here</a></p> <p>Another example is BLEUART which have callback functions:</p> <pre><code>/********************************************************************* This is an example for our nRF52 based Bluefruit LE modules Pick one up today in the adafruit shop! Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! MIT license, check LICENSE for more information All text above, and the splash screen below must be included in any redistribution *********************************************************************/ /* * This sketch demonstrate the central API(). A additional bluefruit * that has bleuart as peripheral is required for the demo. */ #include &lt;bluefruit.h&gt; BLEClientBas clientBas; // battery client BLEClientDis clientDis; // device information client BLEClientUart clientUart; // bleuart client void setup() { Serial.begin(115200); // while ( !Serial ) delay(10); // for nrf52840 with native usb Serial.println(&quot;Bluefruit52 Central BLEUART Example&quot;); Serial.println(&quot;-----------------------------------\n&quot;); // Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1 // SRAM usage required by SoftDevice will increase dramatically with number of connections Bluefruit.begin(0, 1); Bluefruit.setName(&quot;Bluefruit52 Central&quot;); // Configure Battery client clientBas.begin(); // Configure DIS client clientDis.begin(); // Init BLE Central Uart Serivce clientUart.begin(); clientUart.setRxCallback(bleuart_rx_callback); // Increase Blink rate to different from PrPh advertising mode Bluefruit.setConnLedInterval(250); // Callbacks for Central Bluefruit.Central.setConnectCallback(connect_callback); Bluefruit.Central.setDisconnectCallback(disconnect_callback); /* Start Central Scanning * - Enable auto scan if disconnected * - Interval = 100 ms, window = 80 ms * - Don't use active scan * - Start(timeout) with timeout = 0 will scan forever (until connected) */ Bluefruit.Scanner.setRxCallback(scan_callback); Bluefruit.Scanner.restartOnDisconnect(true); Bluefruit.Scanner.setInterval(160, 80); // in unit of 0.625 ms Bluefruit.Scanner.useActiveScan(false); Bluefruit.Scanner.start(0); // // 0 = Don't stop scanning after n seconds } /** * Callback invoked when scanner pick up an advertising data * @param report Structural advertising data */ void scan_callback(ble_gap_evt_adv_report_t* report) { // Check if advertising contain BleUart service if ( Bluefruit.Scanner.checkReportForService(report, clientUart) ) { Serial.print(&quot;BLE UART service detected. Connecting ... &quot;); // Connect to device with bleuart service in advertising Bluefruit.Central.connect(report); }else { // For Softdevice v6: after received a report, scanner will be paused // We need to call Scanner resume() to continue scanning Bluefruit.Scanner.resume(); } } /** * Callback invoked when an connection is established * @param conn_handle */ void connect_callback(uint16_t conn_handle) { Serial.println(&quot;Connected&quot;); Serial.print(&quot;Dicovering Device Information ... &quot;); if ( clientDis.discover(conn_handle) ) { Serial.println(&quot;Found it&quot;); char buffer[32+1]; // read and print out Manufacturer memset(buffer, 0, sizeof(buffer)); if ( clientDis.getManufacturer(buffer, sizeof(buffer)) ) { Serial.print(&quot;Manufacturer: &quot;); Serial.println(buffer); } // read and print out Model Number memset(buffer, 0, sizeof(buffer)); if ( clientDis.getModel(buffer, sizeof(buffer)) ) { Serial.print(&quot;Model: &quot;); Serial.println(buffer); } Serial.println(); }else { Serial.println(&quot;Found NONE&quot;); } Serial.print(&quot;Dicovering Battery ... &quot;); if ( clientBas.discover(conn_handle) ) { Serial.println(&quot;Found it&quot;); Serial.print(&quot;Battery level: &quot;); Serial.print(clientBas.read()); Serial.println(&quot;%&quot;); }else { Serial.println(&quot;Found NONE&quot;); } Serial.print(&quot;Discovering BLE Uart Service ... &quot;); if ( clientUart.discover(conn_handle) ) { Serial.println(&quot;Found it&quot;); Serial.println(&quot;Enable TXD's notify&quot;); clientUart.enableTXD(); Serial.println(&quot;Ready to receive from peripheral&quot;); }else { Serial.println(&quot;Found NONE&quot;); // disconnect since we couldn't find bleuart service Bluefruit.disconnect(conn_handle); } } /** * Callback invoked when a connection is dropped * @param conn_handle * @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h */ void disconnect_callback(uint16_t conn_handle, uint8_t reason) { (void) conn_handle; (void) reason; Serial.print(&quot;Disconnected, reason = 0x&quot;); Serial.println(reason, HEX); } /** * Callback invoked when uart received data * @param uart_svc Reference object to the service where the data * arrived. In this example it is clientUart */ void bleuart_rx_callback(BLEClientUart&amp; uart_svc) { Serial.print(&quot;[RX]: &quot;); while ( uart_svc.available() ) { Serial.print( (char) uart_svc.read() ); } Serial.println(); } void loop() { if ( Bluefruit.Central.connected() ) { // Not discovered yet if ( clientUart.discovered() ) { // Discovered means in working state // Get Serial input and send to Peripheral if ( Serial.available() ) { delay(2); // delay a bit for all characters to arrive char str[20+1] = { 0 }; Serial.readBytes(str, 20); clientUart.print( str ); } } } } </code></pre> <p>The following helps set the callback functions:</p> <pre><code>clientUart.setRxCallback(bleuart_rx_callback); ... Bluefruit.Central.setConnectCallback(connect_callback); ... Bluefruit.Central.setDisconnectCallback(disconnect_callback); </code></pre> <p>Tracing back the libraries I found :</p> <pre><code>void BLEPeriph::setConnectCallback( ble_connect_callback_t fp ) { _connect_cb = fp; } void BLEPeriph::setDisconnectCallback( ble_disconnect_callback_t fp ) { _disconnect_cb = fp; } </code></pre> <p>But I can't understand how this initializes the calling of the connect or disconnect function while getting a new connection or break in connection respectively.</p>
<p>All a callback function assignment does is link an internal pointer to the function that you provide.</p> <p>Any time the callback is needed to be called the code just uses the pointer that your function has been assigned to.</p> <p>Thus <code>_connect_cb</code> and <code>connect_callback()</code> are one and the same thing. Any time <code>connect_callback()</code> would be expected to be used <code>_connect_cb()</code> is used instead.</p> <p>It is, in effect, just creating an internal alias to your code then using that alias to call your code when it needs to.</p>
90837
|arduino-uno|power|dht11|
DHT11 stops working when power comes from a power supply board
2022-09-25T16:10:23.770
<p>I had a mini project with a DHT11, a temperature and humidity sensor, working perfectly on my Arduino UNO clone. Then, I bought a power supply board, that can feed the sensor with the 5V it requires, but for some reason, it does not work. Powering the sensor with the Arduino makes it get the correct values, powering it with the board makes it to stop working at all.</p> <p>I have used a multimeter for checking the volts and amps. The readings on the sensor are the same with the Arduino and the board, 5V, but the amps are not. It seems that the sensor only uses power for an instant, while &quot;sensing&quot;. Using Arduino, a 1.62mA current flows to the sensor and then drops to 0, but using the board it never gets higher than 0.001mA.</p> <p>I repeated the test with different wires, protoboards and even power supply boards. I have three of them, all working apparently ok and reading the same on the multimeter. The board have the jumpers in the correct position: 5V.</p> <p>I am just an amateur learning how electronics works, and I do not understand what is happening here. Some ideas?</p> <p>Working:</p> <p><a href="https://i.stack.imgur.com/Hryuk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hryuk.jpg" alt="enter image description here" /></a></p> <p>Not working:</p> <p><a href="https://i.stack.imgur.com/7UfKw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7UfKw.jpg" alt="enter image description here" /></a></p> <p>I don't think the problem is in the code, but just in case...</p> <pre><code>#include &quot;DHTStable.h&quot; DHTStable DHT; #define DHT11_PIN 5 void setup() { Serial.begin(115200); Serial.println(__FILE__); Serial.print(&quot;LIBRARY VERSION: &quot;); Serial.println(DHTSTABLE_LIB_VERSION); Serial.println(); Serial.println(&quot;Type,\tstatus,\tHumidity (%),\tTemperature (C)&quot;); } void loop() { // READ DATA Serial.print(&quot;DHT11, \t&quot;); int chk = DHT.read11(DHT11_PIN); switch (chk) { case DHTLIB_OK: Serial.print(&quot;OK,\t&quot;); break; case DHTLIB_ERROR_CHECKSUM: Serial.print(&quot;Checksum error,\t&quot;); break; case DHTLIB_ERROR_TIMEOUT: Serial.print(&quot;Time out error,\t&quot;); break; default: Serial.print(&quot;Unknown error,\t&quot;); break; } // DISPLAY DATA Serial.print(DHT.getHumidity(), 1); Serial.print(&quot;,\t&quot;); Serial.println(DHT.getTemperature(), 1); delay(2000); } </code></pre>
<p>In your question in the image below your grounds are not connected. The solution to your problem is to connect the ground (and only the ground, not the +5V) of your external power supply to the ground of the Arduino and the DHT11 will probably work again.</p> <p><strong>A bit of background</strong></p> <p>Sensors needs to be connected to the same ground as the Arduino. This is true in general with all parts of an electronic circuit. Ground functions as a fixed, common, reference voltage by which other signals (such as the digital data that's exchanged between the DHT11 sensor and the Arduino) are measured.</p> <p>By connecting grounds, you make sure that a &quot;high&quot; that is output by the DHT11 is read as a &quot;high&quot; by Arduino and vice versa. When grounds are not connected, voltages between two parts of the circuit would &quot;float&quot; relative to each other and they would not be able to communicate. <a href="https://www.build-electronic-circuits.com/what-is-ground/" rel="nofollow noreferrer">This link</a> explains a bit more.</p>
90839
|usb|arduino-micro|
Why wont my custom Arduino-Micro-based board receive power via USB?
2022-09-25T17:20:41.200
<p>UPDATE: I believe I have mostly solved the power issues, but now have USB connectivity issues described in EDIT 3 at the bottom.</p> <p>I designed and printed a PCB for my MIDI controller project with a modified Arduino Micro microcontroller built in. I swapped out the USB Micro for a USB-C type port (just using the 2.0 protocol), but when I plug it in, after programming the bootloader to the ATMEGA32U4 via &quot;Arduino as ISP&quot; with an Uno as ISP to the ICSP of my board, my board seems to get no power from the USB bus (the power LED doesn't light up, nor is it recognized as a USB device), but it does get power over the ICSP and I got a success message after programming it with the Uno.</p> <p>I have tried many USB cables, including USB-C ones I know to be 2.0 compatible and USB Micro cables (which have been tested with regular Arduino Micros) with micro-to-C adapters, but still get nothing. My PCB has full parity with my SCH file, and I tested it on multiple of these boards that I got printed, so I am pretty sure I must have messed something up in the schematic or in component selection (not all the exact components from the official Arduino Micro schematic were available at JLCPCB where I had mine printed so I made some substitutions).</p> <p>Can anyone help me figure out what the issue might be?</p> <p>EDIT 1: So I found out that the power is coming in through the USB, its reading 5V at the USB pins, 5V on either side of the fuse F1 and the VUSB pin of the T1 FDN340P/PMV48XP, but 0V at both the VIN and +5V pins of the same T1, so that seems to be the problem component? I'm using a PMV48XP in that position, not sure if I messed that up somehow? I'm a bit out of my depth here I think</p> <p>I've uploaded the schematic and the component list below: <a href="https://i.stack.imgur.com/UjIkH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UjIkH.jpg" alt="Edited Arduino Micro Schematic" /></a></p> <p>Components:</p> <pre><code>| Designator | Value | Component | |:--------------------------------------------------------|:-------------------------|:--------------------------| | C_ARD_1, C_ARD_2, C_ARD_6, C_ARD_9, C_ARD_10, C_ARD_11 | 100n | CL05B104KO5NNNC | | C_ARD_3, C_ARD_14 | 22u | RVT22UF16V67RV0017 | | C_ARD_4, C_ARD_5, C_ARD_7 | 1uF | CL05A105KA5NQNC | | C_ARD_12, C_ARD_13 | 22pF | 0402CG220J500NT | | D_ARD_2 | CD1206-S01575 | CDSU4148-HF | | F1 | MF-MSMF050-2 500mA | MF-MSMF050-2 | | J3 | USB_C_Receptacle_USB2.0 | KH-TYPE-C-16P | | L1 | green | 19-217/GHC-YR1S2/3T | | L2 | MH2029-300Y | BLM21PG300SN1D | | ON1 | blue | 19-217/BHC-ZL1M2RY/3T | | R_ARD_1, R_ARD_2, R_ARD_4, R_ARD_9 | 10K | 0402WGF1002TCE | | R_ARD_5, R_ARD_6, R_ARD_7, R_ARD_8 | 1K | 0402WGF1001TCE | | R_ARD_10, R_ARD_11 | 5.1k | 0402WGF5101TCE | | RP3 | 22R | 4D03WGJ0220T5E | | RX1, TX1 | yellow | 19-213/Y2C-CQ2R2L/3T(CY) | | T1 | FDN340P/PMV48XP | PMV48XP | | T2 | PMV48XP | PMV48XP | | U1 | ATMEGA32U4-XUMU | ATMEGA32U4-MU | | U2 | NCP1117-5 | NCP1117ST50T3G | | U4 | LP2985-33DBVR | LP2985-33DBVR | | Y3 | 16MHz KX-7 | 3225-16.00-10-10-10/A | | Z1, Z2 | CG0603MLC-05E | EZJZ0V500AA | </code></pre> <p>EDIT 2: I think I found the problem. It looks like something got messed up when I was choosing the footprints of the MOSFET transistors T1 and T2. Here is a screenshot from the datasheet of the PMV48XP datasheet showing the pinning info: <a href="https://i.stack.imgur.com/2AWTc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2AWTc.png" alt="PMV48XP Pinning Info" /></a> and now here is a screenshot of the relevant part of my PCB file: <a href="https://i.stack.imgur.com/h1v9K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h1v9K.png" alt="enter image description here" /></a> So according to my schematic (again, based on the official Arduino Micro SCH, so I'm assuming its correct?) T1 Gate should be VIN, T1 Source should be +5V, T1 Drain should be VUSB. On my PCB T1 Gate is actually VUSB, T1 Source is +5V, T1 Drain is actually VIN. So it looks like the Gate and Drain pins got swapped between my SCH and my PCB. Same story for T2. Can anyone with more knowledge confirm that the connections outlined in the schematic are correct? And whether that would explain the problems I've described?</p> <p>EDIT 3: I have de-soldered T1 and T2, which were in indeed incorrectly wired. I have shorted the contacts between VUSB and +5V on the footprint of T1 and the board is getting power as it is supposed to.</p> <p>Now I have a new issue which is that after I have programmed the board via ICSP (using the Arduino as ISP method, burning the Arduino Micro bootloader to it), when I plug the board into my computer (again, testing with a variety of cables and ports), my computer won't recognize it as a USB device. I'm not sure if this is a related problem to my previous one (and maybe I should make a new post if not?) or where I am going wrong now.</p>
<p>I think you need to understand a little bit of how the T1 and T2 functions in order to troubleshoot. The purpose of T1 is when power is supplied via VBUS, and when Vin is not presented (i.e. at 0v), the VUSB is directly supplied as the 5V(bypassing the NCP1117 regulator). However, when you power via Vin and it is at least higher than 5V(likely at 7V), it will turn off the T1 and cut off the VUSB supply, and T2 is on, Vin is apply as the input to the NCP1117.</p> <p>So with this in mind, if you connect your board via VBUS but can't get 5V, then you either has a malfunction T1 or you had connect T1 drain and source wrongly. However, if you supply your board via Vin, and don't get the 5V, there could be that your Vin is not high enough to turn on the T2, or your had wrong connection on T2.</p>
90840
|arduino-uno|arduino-nano|
How do I go about pausing/stopping the timer1 task setup in this library, so I can use timer1 for something else in my code
2022-09-25T18:18:23.717
<p>So I want to use this library, that uses timer1 to fetch samples from analog input on pin A0. It works great, and so after proper detection I'd like to perform all kinds of different tasks. But for those I need timer1 again and I think this library keeps it's timer1 routine continuously running. (Am I right?)</p> <p>(EDIT: clarification) I think therefore a different library using timer1 won't work as expected. That's why after the first library's task is done, I'd like to free up timer1 for the second library.)</p> <pre><code>/* Original text created by Jacob Rosenthal: The Goertzel algorithm is long standing so see http://en.wikipedia.org/wiki/Goertzel_algorithm for a full description. It is often used in DTMF tone detection as an alternative to the Fast Fourier Transform because it is quick with low overheard because it is only searching for a single frequency rather than showing the occurrence of all frequencies. This work is entirely based on the Kevin Banks code found at http://www.embedded.com/design/configurable-systems/4024443/The-Goertzel-Algorithm so full credit to him for his generic implementation and breakdown. I've simply massaged it into an Arduino library. I recommend reading his article for a full description of whats going on behind the scenes. Created by Jacob Rosenthal, June 20, 2012. Released into the public domain. Modifications 6v6gt 09.09.2019 1. Restructure instance variables to permit multiple instances of class. 2. Make sample array static to share it between instances 3. Pass in sample array as pointer so it can be reused outside class. 4. Drive ADC by timer1 instead of polling ADC in loop() and reduce resolution to 8 bits. 5. Separate coeeficient calculation from constructor because it now relies on data unknown at invocation (sample rate) 5. Some consolidation of methods. 6. Software &quot;as is&quot;. No claims made about its suitability for any use. Use at your own risk. Special care required if you use other analog inputs or an AVR chip other than ATmega328P (Uno etc.). */ #include &quot;Arduino.h&quot; #include &quot;Goertzel.h&quot; // set by Goertzel::init() uint8_t * Goertzel::testData; // static declaration in .h uint16_t Goertzel::N ; // ditto uint16_t Goertzel::SAMPLING_FREQUENCY ; // ditto volatile bool Goertzel::testDataReady = false ; // static declaration in .h //ADC interrupt service routine ISR(ADC_vect) { // load sample buffer on sample conversion. static uint16_t sampleIndex = 0 ; if ( ! Goertzel::testDataReady ) { if ( sampleIndex &lt; Goertzel::N ) { *(Goertzel::testData + sampleIndex++ ) = ADCH ; // 8 bits. Direct adressing into byte buffer } else { Goertzel::testDataReady = true ; // make buffer available to consumer sampleIndex = 0 ; } } TIFR1 = _BV(ICF1); // reset interrupt flag } // constructor Goertzel::Goertzel(float TARGET_FREQUENCY ) { _TARGET_FREQUENCY = TARGET_FREQUENCY; //should be integer of SAMPLING_RATE/N } //static method void Goertzel::init( uint8_t *sampleArray , uint16_t sampleArraySize, uint16_t sampleFrequency ) { // set up sample array, number of samples and sample frequency. // load class static variables testData = sampleArray ; N = sampleArraySize ; SAMPLING_FREQUENCY = sampleFrequency ; // initialise ADC and Timer1. Timer1 triggers ADC at frequency SAMPLING_FREQUENCY. // ISR(ADC_vect) called when conversion complete. cli() ; // Setup Timer1 for chosen sampling frequency. TCCR1A = 0; TCCR1B = _BV(CS10) | // Bit 2:0 – CS12:0: Clock Select = no prescaler _BV(WGM13) | // WGM 12 = CTC ICR1 Immediate MAX _BV(WGM12); // WGM 12 ditto ICR1 = ( (F_CPU ) / SAMPLING_FREQUENCY ) - 1; // Setup ADC for triggering by timer1; 8bit resolution; Analog Port PC0 (pin A0) ADMUX ADMUX = _BV(REFS0) ; // Fixed AVcc reference voltage for ATMega328P ADMUX |= _BV(ADLAR) ; // left adjust conversion result in ADCH (8bit) DIDR0 |= _BV(ADC0D); // DIDR0 Digital Input Disable Register 0 ADCSRB = _BV(ADTS2) | // Bit 2:0 ADTS[2:0]: ADC Auto Trigger Source _BV(ADTS1) | // Timer/Counter1 Capture Event _BV(ADTS0); // ditto ADCSRA = _BV(ADEN) | // Bit 7 ADEN: ADC Enable _BV(ADSC) | // Bit 6 ADSC: ADC Start Conversion _BV(ADATE) | // Bit 5 ADATE: ADC Auto Trigger Enable _BV(ADIE) | // _BV(ADPS0) | // Bits 2:0 ADPS[2:0]: ADC Prescaler Select Bits (div 8 ) _BV(ADPS1); // ditto sei() ; } // instance method void Goertzel::getCoefficient( void ) { // previously in constructor. Now SAMPLING_FREQUENCY unknown at invocation time. float omega = (2.0 * PI * _TARGET_FREQUENCY) / SAMPLING_FREQUENCY; coeff = 2.0 * cos(omega); } // instance method float Goertzel::detect() { Q2 = 0; Q1 = 0; for ( uint16_t index = 0; index &lt; N; index++) { // byte sample is ( *( testData + index ) ); float Q0; Q0 = coeff * Q1 - Q2 + (float) ( *( testData + index ) - 128 ) ; // 128 for 8bit; 512 for 10bit resolution. Q2 = Q1; Q1 = Q0; } /* standard Goertzel processing. */ float magnitude = sqrt(Q1 * Q1 + Q2 * Q2 - coeff * Q1 * Q2); return magnitude ; } </code></pre> <p>I'm new to using timers on Arduino, but I want to understand and learn more about it. So I'm reading up on it. Seeing that it's not the easiest subject to wrap my head around I'd like to ask for some directions.</p> <p>On this splendid page I gathered some examples of stopping / disabling timer1.</p> <pre><code> TCCR1B = 0; TIMSK1 = 0; // disable Timer1 Interrupt </code></pre> <p><a href="https://www.gammon.com.au/timers" rel="nofollow noreferrer">Nick Gammons Timer info page</a></p> <p>However I don't completely recognise the usage of the library's timer names, registers, variables yet. And so I'm unsure what part of the code is doing what exactly, ie where, how and when the timer starts. And therefore I'm equally unsure how to go about stopping it when the task is done, and to start it again when a new detection is needed. It seems there is TCCR1A, TCCR1B, cli() and sei() that have something to do with it and ISR(ADC_vect). One of you probably knows ;)</p> <p>EDIT: Reading the suggested <a href="https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf" rel="nofollow noreferrer">ATmega328p datasheet</a> I found out a little bit more about the following abbreviations:</p> <pre><code>cli // disable interrupts during timed sequence __disable_interrupt(); sei // Set global Interrupt Enable __enable_interrupt(); TCNT1 // Timer/Counter (setting 0 will reset) TIFR1 // Timer Interrupt Flag Register TCCR1A // Timer/Counter Control Register 1a (setting 0 will reset) TCCR1B // Timer/Counter Control Register 1b (setting 0 will reset) TIMSK1 // Timer Interrupt Mask Register ICR1 // Input Capture Register ICF1 // Input Capture Flag ICP1 // Input Capture Pin WGM // Waveform Generation Mode CS // Clock Select Bits (prescaler??) F_CPU // The CPU speed (What is the default value? 8000000??? 1000000??? 16000000???) DIDR1/DIDR0 // Digital Input Disable Registers (if left enabled they will use excessive power when Analog input is floating or close to VCC/2) ADMUX // ADC Multiplexer Selection Register REFS1 &amp; REFS0 // Voltage Reference Selection ADLAR // ADC Left Adjust Result MUX ADEN // ADC Enable ADSC // ADC Start Conversion ADATE // ADC Auto Trigger Enable ADTS // ADC Trigger Source Select ADCSRB // ADIE // ADC Conversion Complete Interrupt Enable ADPS0 &amp; ADPS0 // ADC Prescaler Select Bits </code></pre> <p>But hasn't really lightened things up entirely for me. What is _BV? for example.</p> <p>EDIT: I think I'm starting to make sense of it more. Am I right here(??):</p> <pre><code>ADMUX = (0b00 &lt;&lt; REFS0) | (1 &lt;&lt; ADLAR) | (0b00000 &lt;&lt; MUX0); Is the same as: ADMUX = (0b00 &lt;&lt; REFS0); // 0 shift has no effect so can be omitted ADMUX |= (1 &lt;&lt; ADLAR); ADMUX |= (0b00000 &lt;&lt; MUX0); // 0 shift has no effect so can be omitted Is de same as: ADMUX = (1 &lt;&lt; REFS0); // can be omitted ADMUX |= (1 &lt;&lt; ADLAR); ADMUX |= (1 &lt;&lt; MUX0); // can be omitted is the same as: ADMUX = _BV(REFS0); // can be omitted ADMUX |= _BV(ADLAR); ADMUX |= _BV(MUX0); // can be omitted Is the same as: ADMUX = (1 &lt;&lt; ADLAR); Is the same as: ADMUX = _BV(ADLAR); </code></pre> <p>Understanding it all would be great, but may be unnecessary. If only I'd know how I can stop and free Timer1 usage for other purposes. Starting it all up again would be easier I guess ;)</p>
<p>Time hasn't been on my side lately. But here is the code I've come up with so far. Needs testing still to see if it solves all my problems but in regards to my original question this seems to hold the answer I was looking for. Later on I might add some more info/links to register settings, hex/binary/ascii tables, bitwise operations and what they all do. But the manual is your friend pretty much.</p> <p>Alright then. First of all this print function comes in handy:</p> <pre><code>// Handy while experimenting with all different bitwise operations and settings void printRegSettings() { const String regNames[8] = {&quot;TCCR1A&quot;, &quot;TCCR1B&quot;, &quot;ICR1&quot;, &quot;ADMUX&quot;, &quot;DIDR0&quot;, &quot;ADCSRA&quot;, &quot;ADCSRB&quot;, &quot;TIFR1&quot;}; //other: &quot;TCNT1&quot;, &quot;OCR1A&quot;, &quot;OCR1B&quot;, &quot;TIMSK1&quot; uint8_t regVars[8] = {TCCR1A, TCCR1B, ICR1, ADMUX, DIDR0, ADCSRA, ADCSRB, TIFR1}; //other: TCNT1, OCR1A, OCR1B, TIMSK1 for (uint8_t index = 0; index &lt; sizeof(regVars)/sizeof(regVars[0]); index++) { Serial.print(regNames[index]+&quot; = 0b&quot;); for (uint8_t i = 8; i &gt; 0; i--) { Serial.print(bitRead(regVars[index], i-1)); } Serial.write('\n'); } } </code></pre> <p>Next put all library register settings in function, notice the boolean in the end, for emptying the ISR (later described):</p> <pre><code>void dtmfTimerSetup () { TCCR1A = 0; TCCR1B = _BV(CS10) | // Bit 2:0 – CS12:0: Clock Select = no prescaler _BV(WGM13) | // WGM 12 = CTC ICR1 Immediate MAX _BV(WGM12); // WGM 12 ditto ICR1 = ( (F_CPU ) / 9600 ) - 1; ADMUX = _BV(REFS0) ; // Fixed AVcc reference voltage for ATMega328P ADMUX |= _BV(ADLAR) ; // left adjust conversion result in ADCH (8bit) DIDR0 |= _BV(ADC0D); // DIDR0 Digital Input Disable Register 0 ADCSRB = _BV(ADTS2) | // Bit 2:0 ADTS[2:0]: ADC Auto Trigger Source _BV(ADTS1) | // Timer/Counter1 Capture Event _BV(ADTS0); // ditto ADCSRA = _BV(ADEN) | // Bit 7 ADEN: ADC Enable _BV(ADSC) | // Bit 6 ADSC: ADC Start Conversion _BV(ADATE) | // Bit 5 ADATE: ADC Auto Trigger Enable //_BV(ADIE) | // _BV(ADPS0) | // Bits 2:0 ADPS[2:0]: ADC Prescaler Select Bits (div 8 ) _BV(ADPS1); // ditto Goertzel::dtmfListenerISR = true; } </code></pre> <p>Next add a function to clear all these settings. Initial values of registers is 0 as far as I checked. So setting them zero does the job. Again notice the boolean false this time.</p> <pre><code>void clearTimerSettings() { //Empty Goertzel dtmf interrupt ISR routine Goertzel::dtmfListenerISR = false; //reset all altered registers to initial value 0 Serial.println(F(&quot;***CLEARING ALL BIT SETTINGS***&quot;)); TCCR1A = TCCR1B = ICR1 = ADMUX = DIDR0 = ADCSRA = ADCSRB = TIFR1 = 0; // pauze but don't erase current interrupt settings: // bitClear(ADCSRA, ADIE); //risk interference when different timer adc library sets bit again } </code></pre> <p>In Goertzel.h Add this static bool declaration to class Goertzel public:</p> <pre><code>static volatile bool Goertzel::dtmfListenerISR; </code></pre> <p>Add boolean declaration to Goertzel.cpp and add 'if statement' inside ISR(ADC_vect) to only execute interrupt if dtmfListenerISR is true.</p> <pre><code>volatile bool Goertzel::dtmfListenerISR; //ADC interrupt service routine ISR(ADC_vect) { //if dtmfListenerISR is false, this code is skipped, freeing timer1 for other purposes if (Goertzel::dtmfListenerISR) { // load sample buffer on sample conversion. static uint16_t sampleIndex = 0 ; if ( ! Goertzel::testDataReady ) { if ( sampleIndex &lt; Goertzel::N ) { *(Goertzel::testData + sampleIndex++ ) = ADCH ; // 8 bits. Direct adressing into byte buffer } else { Goertzel::testDataReady = true ; // make buffer available to consumer sampleIndex = 0 ; } } TIFR1 = _BV(ICF1); // reset interrupt flag } } </code></pre> <p>Finally use these functions like this in your sketch. The setup can be done in setup but the clearing should take place in your void loop of course, once the library and timer interrupt have finished their job and you want another library / timer routine to take over. Just for testing I put them all inside a setup and a simple sketch now.</p> <pre><code>void setup() { Serial.begin(115200); //setup/initialize timer interrupt routine: dtmfTimerSetup(); //FOR TESTING: check and print current settings: printRegSettings(); //clear timer interrupt routine; clearTimerSettings(); printRegSettings(); //only for testing purposes } void loop() { // put your main code here, to run repeatedly: } </code></pre> <p>Ofcourse for the other libraries using timer1 you should do the same: setup functions with register settings / cleanup and declare/set boolean for ISR part. There might be some overkill here, but so far I didn't find a more elegant way of achieving all this.</p>
90845
|arduino-mega|multiplexer|
Voltage reading problem in Arduino mega based 10 cannel battery capacity tester
2022-09-26T08:50:04.100
<p>I want to make a 10 channels Arduino mega-based battery capacity tester using 4.7 ohms 10w resistors controlling them with IRFZ44n MOSFETs with respected digital pins. An 8.4V battery powers the Arduino (do not consider the buck converter in the picture). I am debugging my project step by step. When I read voltages of individual batteries by corresponding analog pins without turning On 'MOSFET-Gate pins' then Arduino measures the voltages correctly but when I turn on the gate pins then Arduino measures voltage incorrectly. Meaning if I connect a battery with an analog pin and a multimeter at the same time and the value is pretty much same. Like 3.70 volt for the multimeter and 3.72 for analog pin but when I turn On the gatepin of the MOSFET then Arduino value is like 3.07V and Multimeter value is 3.48V. Thanks in advance.</p> <p>Here is the Circuit Diagram of my project: <a href="https://i.stack.imgur.com/0xeSN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0xeSN.jpg" alt="enter image description here" /></a></p> <p>Simple version to understand: <a href="https://i.stack.imgur.com/ZidlV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZidlV.jpg" alt="enter image description here" /></a></p> <p>Code:</p> <pre class="lang-cpp prettyprint-override"><code>long readVcc() { // Read 1.1V reference against AVcc // set the reference to Vcc and the measurement to the internal 1.1V reference #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) ADMUX = _BV(MUX5) | _BV(MUX0) ; #else ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #endif ADCSRB &amp;= ~_BV(MUX5); delay(2); // Wait for Vref to settle ADCSRA |= _BV(ADSC); // Start conversion while (bit_is_set(ADCSRA,ADSC)); // measuring uint8_t low = ADCL; // must read ADCL first - it then locks ADCH uint8_t high = ADCH; // unlocks both long result = (high&lt;&lt;8) | low; result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000 //1126400L internalRefVolt(1.1) * 1023 * 1000; code can more precse by calculating internalRefVolt(1.1) return result; // Vcc in millivolts } void setup() { Serial.begin(115200); delay(3000); pinMode(22,OUTPUT);//***Mosfet Gate Pins******** pinMode(23,OUTPUT); pinMode(24,OUTPUT); pinMode(25,OUTPUT); pinMode(26,OUTPUT); pinMode(27,OUTPUT); pinMode(28,OUTPUT); pinMode(29,OUTPUT); pinMode(30,OUTPUT); pinMode(31,OUTPUT); digitalWrite(22,LOW);//***Initially low the Mosfet Gate Pins******** digitalWrite(23,LOW); digitalWrite(24,LOW); digitalWrite(25,LOW); digitalWrite(26,LOW); digitalWrite(27,LOW); digitalWrite(28,LOW); digitalWrite(29,LOW); digitalWrite(30,LOW); digitalWrite(31,LOW); } /**********************************Void Loop******************************************************/ void loop() { float voltRef = readVcc() / 1000.0; digitalWrite(22,HIGH);//*** High the Mosfet Gate Pins******** digitalWrite(23,HIGH); digitalWrite(24,HIGH); digitalWrite(25,HIGH); digitalWrite(26,HIGH); digitalWrite(27,HIGH); digitalWrite(28,HIGH); digitalWrite(29,HIGH); digitalWrite(30,HIGH); digitalWrite(31,HIGH); float volt0 = analogRead(A0)*(voltRef/1024); delay(10); volt0 = analogRead(A0)*(voltRef/1024); /* if(volt0&gt;3.0){ digitalWrite(22,HIGH); // High = Mosfet ON digitalWrite(36,HIGH); // High = LED Turn OFF }*/ float volt1 = analogRead(A1)*(voltRef/1024); delay(10); volt1 = analogRead(A1)*(voltRef/1024); float volt2 = analogRead(A2)*(voltRef/1024); delay(10); volt2 = analogRead(A2)*(voltRef/1024); float volt3 = analogRead(A3)*(voltRef/1024); delay(10); volt3 = analogRead(A3)*(voltRef/1024); float volt4 = analogRead(A4)*(voltRef/1024); delay(10); volt4 = analogRead(A4)*(voltRef/1024); float volt5 = analogRead(A5)*(voltRef/1024); delay(10); volt5 = analogRead(A5)*(voltRef/1024); float volt6 = analogRead(A6)*(voltRef/1024); delay(10); volt6 = analogRead(A6)*(voltRef/1024); float volt7 = analogRead(A7)*(voltRef/1024); delay(10); volt7 = analogRead(A7)*(voltRef/1024); float volt8 = analogRead(A8)*(voltRef/1024); delay(10); volt8 = analogRead(A8)*(voltRef/1024); float volt9 = analogRead(A9)*(4.95/1024); delay(10); volt9 = analogRead(A9)*(4.95/1024); //***************************************************************************** Serial.print(&quot;B0= &quot;); Serial.println(volt0); Serial.print(&quot;B1= &quot;); Serial.println(volt1); Serial.print(&quot;B2= &quot;); Serial.println(volt2); Serial.print(&quot;B3= &quot;); Serial.println(volt3); Serial.print(&quot;B4= &quot;); Serial.println(volt4); Serial.print(&quot;B5= &quot;); Serial.println(volt5); Serial.print(&quot;B6= &quot;); Serial.println(volt6); Serial.print(&quot;B7= &quot;); Serial.println(volt7); Serial.print(&quot;B8= &quot;); Serial.println(volt8); Serial.print(&quot;B9= &quot;); Serial.println(volt9); Serial.println(&quot;&quot;); Serial.println(&quot;==========================&quot;); delay(500); } </code></pre>
<p>The main problem was the battery holder default wire, those wires were have high resistance. After changing those wire the problem was solved. Thank you everyone</p>
90857
|arduino-ide|arduino-nano|uploading|
Can't upload sketch after overheating
2022-09-27T15:02:24.000
<p>I'm using an Arduino nano, after an unfortunate event, The mega chip heat up and when I tried touching it, it burned my finger. After that, I connected to my laptop's USB port and the computer recognized it. But after I hit the upload button, the RX light flash 3 times and stop, no Loader light and it just stop there, and the IDE says this:</p> <pre><code>Arduino: 1.8.19 (Windows 10), Board: &quot;Arduino Nano, ATmega328P (Old Bootloader)&quot; Sketch uses 2806 bytes (9%) of program storage space. Maximum is 30720 bytes. variables use 44 bytes (2%) of dynamic memory, leaving 2004 bytes for local variables. Maximum is 2048 bytes. An error occurred while uploading the sketch avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x84 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x84 This report would have more information with &quot;Show verbose output during compilation&quot; option enabled in File -&gt; Preferences. </code></pre> <p>Any advice?</p>
<p>Not sure what you did but you probably either overvoltage it or connected it backwards. The odds are extremely high you fried the mega chip. Good news, it is not a total waste, you learned something not to do. It is still good for practicing troubleshooting, if you find what failed great or if you cannot fix it, you will have learned something useful. Atthis point use it for practicing SMD soldering. In the end remove the parts and use the PCB for a template. The recommended solution is to purchase two more, that way if one fails the wate time will be shorter.</p>
90858
|arduino-nano-ble|
Controlling the 5V pin on the Arduino nano 33 BLE
2022-09-27T16:28:33.720
<p>Following the guidance on <a href="https://support.arduino.cc/hc/en-us/articles/360014779679-About-Nano-boards-with-disabled-5-V-pins?_gl=1*1yxmaf9*_ga*NjU4MDE0NTY2LjE2NjQyOTI4MjA.*_ga_NEXN8H46L5*MTY2NDI5MjgyMC4xLjEuMTY2NDI5NTc2NS4wLjAuMA.." rel="nofollow noreferrer">this post </a> I have enabled the 5V pin. That same post suggests that I control that pin with D12, though I find it weird since there is already a D12 pin. When I try and run some code the D12 pin is performing exactly as I expect, but the 5V pin is doing nothing.</p> <p>Looking through the <a href="https://docs.arduino.cc/static/741bbe6b7ce4563049b3b662180471c3/ABX00030-datasheet.pdf" rel="nofollow noreferrer">tech specs</a> it says &quot;<strong>the 5V pin does NOT supply voltage but is rather connected, through a jumper, to the USB power input.</strong>&quot; which I find odd, since if its connected to the power input, should it not be supplying voltage?</p> <p>Could someone clarify if its possible to use the 5V pin like a digital pin, and if so how?</p>
<blockquote> <p>Following the guidance on this post I have enabled the 5V pin. That same post suggests that I control that pin with D12, though I find it weird since there is already a D12 pin. When I try and run some code the D12 pin is performing exactly as I expect, but the 5V pin is doing nothing.</p> </blockquote> <p>5 V pin is the the 12th pin of the PCB</p> <blockquote> <p>Looking through the tech specs it says &quot;the 5V pin does NOT supply voltage but is rather connected, through a jumper, to the USB power input.&quot; which I find odd, since if its connected to the power input, should it not be supplying voltage?</p> </blockquote> <p>it says that the 5V pin is connected to the USB power input through a jumper and the jumper is not connected from factory</p>
90862
|usb|arduino-micro|
Why wont my custom Arduino-Micro-based board connect over USB?
2022-09-27T22:17:24.463
<p>I designed and printed a PCB for my MIDI controller project with a modified Arduino Micro microcontroller essentially built into the design. I swapped out the USB Micro for a USB-C type port (just using the 2.0 protocol). Although I can program the board via ICSP, including getting it to run my Arduino sketches (which I have tested by having it light up the LEDs in a certain pattern, which works as expected), and the fact that it receives power via USB, the problem is that I cannot get the device to connect to my PC over USB - it is not recognized as a USB device, and cannot seem to send or receive data over USB. I'm not sure if I've done something wrong in the design or if I am simply missing something, but could use some advice, as in order to function as intended, the board will need to be able to communicate over USB.</p> <p>I have tested with various USB-A to USB-C cables and USB-A to Micro cables (tested with other Arduinos) and a Micro to USB-C adapter.</p> <p>As per various instructions I found online, I connected pull-down resistors of 5.1k Ohms to CC1 and CC2, left SBU1 and SBU2 unconnected as I was planning to use 2.0 protocols to keep things simple (as a related question, can these actually be used to make use of 3.0+ protocols in a design like this with an ATMEGA32U4? Would this be considered better practice in this case and potentially bypass the error?), and wired up D- and D+ as shown in the schematic below; with a EZJZ0V500AA Varistor between each and GND and running through a 4D03WGJ0220T5E Resistor network (which I don't know much about, including whether this type of component has any polarity? I simply tried to follow how the same sort of component was used in the official Arduino Micro schematics) and finally into pins 3 and 4 of the ATMEGA32U4.</p> <p>This is the original schematic of the board as it was assembled, but as a result of some power issues with this same board which I have since sorted out with help in a separate post <a href="https://arduino.stackexchange.com/questions/90839/why-wont-my-custom-arduino-micro-based-board-receive-power-via-usb">Why wont my custom Arduino-Micro-based board receive power via USB?</a>, I had to bypass the 5V regulator and just use VUSB as +5V, so I will put the updated schematic reflecting these changes below the original (I wouldn't think it would affect this issue, but I'm not that experienced and want to err on the side of providing as many details as possible)</p> <p>Original Schematic: <a href="https://i.stack.imgur.com/OEEKL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OEEKL.jpg" alt="Original Schematic" /></a></p> <p>Revised Schematic: <a href="https://i.stack.imgur.com/qgfHz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qgfHz.jpg" alt="Revised Schematic" /></a></p> <p>Components:</p> <pre><code>| Designator | Value | Component | |:--------------------------------------------------------|:-------------------------|:--------------------------| | C_ARD_1, C_ARD_2, C_ARD_6, C_ARD_9, C_ARD_10, C_ARD_11 | 100n | CL05B104KO5NNNC | | C_ARD_3, C_ARD_14 | 22u | RVT22UF16V67RV0017 | | C_ARD_4, C_ARD_5, C_ARD_7 | 1uF | CL05A105KA5NQNC | | C_ARD_12, C_ARD_13 | 22pF | 0402CG220J500NT | | D_ARD_2 | CD1206-S01575 | CDSU4148-HF | | F1 | MF-MSMF050-2 500mA | MF-MSMF050-2 | | J3 | USB_C_Receptacle_USB2.0 | KH-TYPE-C-16P | | L1 | green | 19-217/GHC-YR1S2/3T | | L2 | MH2029-300Y | BLM21PG300SN1D | | ON1 | blue | 19-217/BHC-ZL1M2RY/3T | | R_ARD_1, R_ARD_2, R_ARD_4, R_ARD_9 | 10K | 0402WGF1002TCE | | R_ARD_5, R_ARD_6, R_ARD_7, R_ARD_8 | 1K | 0402WGF1001TCE | | R_ARD_10, R_ARD_11 | 5.1k | 0402WGF5101TCE | | RP3 | 22R | 4D03WGJ0220T5E | | RX1, TX1 | yellow | 19-213/Y2C-CQ2R2L/3T(CY) | | T1 | FDN340P/PMV48XP | PMV48XP | | T2 | PMV48XP | PMV48XP | | U1 | ATMEGA32U4-XUMU | ATMEGA32U4-MU | | U2 | NCP1117-5 | NCP1117ST50T3G | | U4 | LP2985-33DBVR | LP2985-33DBVR | | Y3 | 16MHz KX-7 | 3225-16.00-10-10-10/A | | Z1, Z2 | CG0603MLC-05E | EZJZ0V500AA | </code></pre>
<p>Well I finally found the source of the problem, many thanks to everyone here who helped me narrow things down and kept pointing me in the right direction. After figuring out that D+ and D- were getting pulled appropriately by the chip I decided to desolder the USB port on the board, cut a USB-A 2.0 cable and solder the leads directly to the board and, suddenly, it worked. After this I realized the problem must have been with the USB port on the board and upon comparing the datasheet to my pcb file, I realized that the footprint I used and the one in the datasheet had the pins laid out in a different order.</p> <p>I feel a bit embarrassed for taking up people's time on such a stupid error I made (and admittedly didn't even provide enough information for anyone to be able to figure out for me, despite all of your patience and helpful advice), but at the same time I am both relieved I figured out the problem and grateful for all the help I got on this post, I'm not sure how long it would have taken me to figure out without your suggestions. I learned a lot about the layout of arduino boards, the purposes of various components in said boards, the importance of double checking footprints, and about better practices for asking for assistance.</p> <p>As a note on &quot;post etiquette&quot; or whatever you would call it, since everyone provided assistance in comments, I didn't see a way to close the post without answering my own question (I am new to posting here), so I hope that is an acceptable way to do so.</p>
90867
|arduino-uno|arduino-nano|bit|
Do these bit settings all mean the same?
2022-09-28T12:05:04.933
<pre><code>ADMUX = ADMUX | _BV(REFS); // uncompounded bitwise OR ADMUX |= _BV(REFS0); // #define _BV(bit) (1 &lt;&lt; (bit)) ADMUX |= bit(REFS0); // #define bit(b) (1UL &lt;&lt; (b)) bitSet(ADMUX, REFS0); // #define bitSet(value, bit) ((value) |= (1UL &lt;&lt; (bit))) sbi(ADMUX, REFS0); // deprecated assembly? ADMUX |= (1 &lt;&lt; REFS0); // shift operator ADMUX |= (1 &lt;&lt; 7); // bit 7 is named REFS0 ADMUX |= 0b10000000; // bin ADMUX |= 0x80; // hex ADMUX |= 128; // dec </code></pre> <p>*under normal 8 bit Arduino circumstances?</p>
<p>You already got an answer in the comments but, just to make double sure, I tried compiling all these statements for an Uno, and they got all translated into the <em>exact same machine code</em>. Well, almost: I had to do some minor adjustments, which I believe are unrelated to the essence of your question. Just for completeness, I changed the following:</p> <ol> <li><p>I replaced REFS0 by REFS1: on an Uno, REFS0 is bit 6, and REFS1 is bit 7.</p> </li> <li><p>I replaced REFS by REFS1, as the former is not defined.</p> </li> <li><p>I #included <code>&lt;compat/deprecated.h&gt;</code>, otherwise I get the error “'<code>sbi</code>' was not declared in this scope”.</p> </li> </ol>
90868
|arduino-uno|arduino-nano|
Do I need to connect a capacitor to AREF if using internal reference? _BV(REFS0)
2022-09-28T13:56:18.980
<p><a href="https://i.stack.imgur.com/XvL8z.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XvL8z.jpg" alt="enter image description here" /></a> This is from the Atmega328p datasheet. But I see no mention of it in practical examples. So when I'm setting up the timer for ADC with:</p> <pre><code>ADMUX = _BV(REFS0); </code></pre> <p>Should I add the cap? Or might it be already there on the arduino's hardware? Also what value is advised? 100nF? Thanks in advance!</p>
<p>According to the datasheet:</p> <blockquote> <p>The voltage reference may be externally decoupled at the AREF pin by a capacitor for better noise performance.</p> </blockquote> <p>So you <em>can</em> but you don't <em>have to</em>. It all depends on how good you want your ADC results to be. 99% of the time it's pointless since what you're reading isn't that accurate, but if you want to add a capacitor anyway then sure, go right ahead.</p> <p>What value capacitor? Well that very much depends on what kind of noise you want to achieve more immunity from. The lower the value the higher the frequency it will help protect you from. You may want to combine multiple capacitors in parallel if you're in a very noisy environment, such as 1nF and 100nF.</p>
90883
|servo|pwm|avr|
How to correctly set PWM to control servo angle in AVR?
2022-09-29T23:17:46.907
<p>I've stumbled upon timer configuration to handle my sg-90 servo and my Arduino UNO.</p> <p><strong>What I did:</strong></p> <ol> <li><em>Set the prescaler to 64 and mode to fast PWM of 16-bit timer.</em></li> <li><em>The frequency is 50hz so the ICR1 is set to 4999.</em></li> <li><em>And now I don't know what to do next to set the values of OCR1A without guessing them.</em></li> </ol> <p>From my understanding: <strong>If the period is now set to 20ms then for sg-90 servo:</strong></p> <p>From documentation: <a href="http://www.ee.ic.ac.uk/pcheung/teaching/DE1_EE/stores/sg90_datasheet.pdf" rel="nofollow noreferrer">http://www.ee.ic.ac.uk/pcheung/teaching/DE1_EE/stores/sg90_datasheet.pdf</a></p> <ul> <li>Angle 0 should be 1ms (1/20 = 0.05), so OCR1A = 4999 * 0.05 ~= 250</li> <li>Angle 90 should be 1.5ms (1.5/20 = 0.075), so OCR1A = 4999 * 0.075 ~= 375</li> <li>Angle 180 should be 2ms (2/20 = 0.1) so OCR1A = 4999 * 0.1 ~= 500</li> </ul> <p><strong>But it doesn't work like that.</strong> I've figured out that values are 125, 370, 615 - I've found these numbers in the internet (not in English language) but that guy didn't explain how he got them.</p> <p>Could someone explain it to me where these numbers come from or where my calculations are incorrect.</p> <p>It's not a problem with servo because with Arduino servo library everything works fine.</p> <p><strong>Solution:</strong></p> <p><strong>The document I've attached is incorrect the pulse range of miliseconds is not 1-2ms but 0.5-2.5ms and everything fits correctly.</strong></p> <p>Below is my current code:</p> <pre><code>#define F_CPU 16000000UL #include &lt;avr/io.h&gt; #include &lt;avr/interrupt.h&gt; #include &lt;util/delay.h&gt; #include &lt;stdbool.h&gt; #define PRESCALER_64 (1 &lt;&lt; CS11) | (1 &lt;&lt; CS10) #define FAST_PWM_A (1 &lt;&lt; WGM11) #define FAST_PWM_B (1 &lt;&lt; WGM13) | (1 &lt;&lt; WGM12) int main(){ TCCR1A = FAST_PWM_A | (1 &lt;&lt; COM1A1); TCCR1B = FAST_PWM_B | PRESCALER_64; ICR1 = (F_CPU / 64 / 50) - 1; DDRB |= (1 &lt;&lt; PB1); while(true){ OCR1A = 125; _delay_ms(2000); OCR1A = 370; _delay_ms(2000); OCR1A = 615; _delay_ms(2000); } } </code></pre>
<p>OK, I figured it out.</p> <p>The document I've attached is incorrect, the pulse range of milliseconds is not 1-2ms but 0.5-2.5ms and everything fits correctly.</p>
90900
|uploading|ide|
Permission denied on upload w/ IDE 2
2022-10-01T18:35:28.563
<p>Dealing with this very common issue on IDE v2.0.0., but not sure why.</p> <p>I should be fine group-wise:</p> <pre class="lang-bash prettyprint-override"><code>adm tty dialout cdrom sudo dip plugdev lpadmin lxd sambashare docker </code></pre> <p>I've also seen numerous suggestions to change the device's permissions directly via <code>chmod a+rw /dev/&lt;device&gt;</code>. This is terrible advice, but nothing is working so far, so I tried it anyway. It also doesn't work, as at some point during the upload process, the device is removed and recreated, resetting the permissions.</p> <p>edit: I've also ensured that ModemManager is not running, and has been purged from the system.</p> <p>Running the IDE as root always fails, including when the <code>--no-sandbox</code> argument is passed.</p> <p>I'm using the AppImage download on Ubuntu 22.04, but I tried the zip download, with the same results.</p> <p>edit: Previously in this spot was a note about this problem not occurring on IDE v. 1.8. That wasn't actually the case - I was just testing with a board that doesn't remove and re-create the device on upload. Using a board where that does occur (Arduino Micro in this case), the error occurs in 1.8 as well.</p> <p>Using <code>avrdude</code> directly (as my normal user account) also works just fine.</p> <p>Additional observation - when the device is recreated by the OS after plugging the Arduino board in, it's first created with <code>crw------- 1 root root</code> permissions, and remains in that state for a very short period of time before switching to <code>crw-rw----+ 1 root dialout</code> permissions, at which point uploads work as expected.</p>
<p>After a <a href="https://chat.stackexchange.com/rooms/139598/discussion-between-timemage-and-x1a4">long debugging session in chat</a>, we've determined that a udev entry installed by the <code>apt</code> package <a href="https://github.com/rickysarraf/laptop-mode-tools" rel="nofollow noreferrer">laptop-mode-tools</a> takes a long time to run, leading to the permissions not settling on the USB device until after the IDE has attempted to upload.</p> <p>This problem happens even when laptop-mode isn't enabled because you're e.g. using AC. You don't need to be actually using a laptop for this problem to occur, as laptop-mode-tools is a generic power-saving package that can be installed anywhere.</p> <p>The udev rule in question is <code>ACTION==&quot;add&quot;, SUBSYSTEM==&quot;usb&quot;, RUN+=&quot;lmt-udev force&quot;</code> in the file <code>/lib/udev/rules.d/99-laptop-mode.rules</code>.</p> <p>Commenting out that udev rule, or changing <code>force</code> to <code>auto</code> resolves the problem for me (without needing to restart udev, or anything else).</p> <p>Larger hammers that can be used to resolve this include setting <code>ENABLE_LAPTOP_MODE_TOOLS</code> to <code>0</code> in <code>/etc/laptop-mode/laptop-mode.conf</code>, or simply removing <code>laptop-mode-tools</code> from the system entirely.</p> <p>@timemage gets the credit for this fix.</p>
90912
|arduino-uno|serial|
Odd characters in serial monitor
2022-10-03T05:45:41.593
<p>I have been recently working on a website that takes input from the arduino ie- temperature and humidity. But there is a fatal problem that I've encountered, the serial monitor spews out some garbage with some actual readings. Is there a way to eliminate this?</p> <pre><code> ╰─λ cat /dev/ttyACM0 T0°C Humidity: 39.00% 00% Temperature: 32.70°C Humidity: 39.00% Temperature: 32.70°C Humidity: 39.00% Temperature: 32.70°C Humidity: 39.00% 00% Temperature: 32.70°C Humidity: 39.00% Temperature: 32.70°C Humidity: 39.00% Temperature: 32.70°C Humidity: 39.00% idit9.00Tempure:70°Humi: 39 emperatu32.7 Huty: 0% idit9.00Tempure:70°umidity.00%Tratu32.7 idit9.00Tempture.70�Humi: 39 empere: 0°Cmidi39.0 atur°C Hum9.00 </code></pre> <p>code-</p> <pre><code>#include &lt;Adafruit_Sensor.h&gt; #include &lt;DHT.h&gt; #include &lt;DHT_U.h&gt; #define DHTPIN 4 #define DHTTYPE DHT11 DHT_Unified dht(DHTPIN, DHTTYPE); uint32_t delayMS; void setup() { Serial.begin(9600); sensor_t sensor; dht.begin(); delayMS = sensor.min_delay / 1000; } void loop() { delay(delayMS); sensors_event_t event; dht.temperature().getEvent(&amp;event); if (isnan(event.temperature)) { Serial.println(F(&quot;Error reading temperature!&quot;)); } else { Serial.print(F(&quot;Temperature: &quot;)); Serial.print(event.temperature); Serial.println(F(&quot;°C&quot;)); } dht.humidity().getEvent(&amp;event); if (isnan(event.relative_humidity)) { Serial.println(F(&quot;Error reading humidity!&quot;)); } else { Serial.print(F(&quot;Humidity: &quot;)); Serial.print(event.relative_humidity); Serial.println(F(&quot;%&quot;)); } } </code></pre> <p>board - Arduino Uno (R3)</p>
<p>As has been noted in the comments, you are trying to read the sensor at a rate that is too fast.</p> <p>Try changing this line:</p> <pre><code>delayMS = sensor.min_delay / 1000; </code></pre> <p>to:</p> <pre><code>delayMS = sensor.min_delay = 1000; </code></pre> <p>or:</p> <pre><code>delayMS = sensor.min_delay = 3000; </code></pre> <p>This will read the sensor at a slower rate and should give you clean output.</p>
90925
|esp32|error|
text section exceeds available space in board
2022-10-04T09:54:42.780
<p>When I compile this code it gives the error mentioned above. I saw online a way to resolve this: <code>Serial.println(F(&quot;...&quot;));</code></p> <p>For fixed string literal I changed it but still didn't work. I'm compiling this for ESP32 board.</p> <pre><code>#include &quot;RMaker.h&quot; #include &quot;WiFi.h&quot; #include &quot;WiFiProv.h&quot; #include &lt;DHT.h&gt; #include &lt;SimpleTimer.h&gt; const char *service_name = &quot;PROV_SmartHome&quot;; const char *pop = &quot;1234&quot;; // define the Chip Id uint32_t espChipId = 5; // define the Node Name char nodeName[] = &quot;ESP32_Smarthome&quot;; // define the Device Names char deviceName_1[] = &quot;Switch1&quot;; char deviceName_2[] = &quot;Switch2&quot;; char deviceName_3[] = &quot;Switch3&quot;; char deviceName_4[] = &quot;Switch4&quot;; // define the GPIO connected with Relays and switches static uint8_t RelayPin1 = 23; //D23 static uint8_t RelayPin2 = 22; //D22 static uint8_t RelayPin3 = 21; //D21 static uint8_t RelayPin4 = 19; //D19 static uint8_t SwitchPin1 = 13; //D13 static uint8_t SwitchPin2 = 12; //D12 static uint8_t SwitchPin3 = 14; //D14 static uint8_t SwitchPin4 = 27; //D27 static uint8_t wifiLed = 2; //D2 static uint8_t gpio_reset = 0; static uint8_t DHTPIN = 18; // D18 pin connected with DHT static uint8_t LDR_PIN = 39; // VN pin connected with LDR /* Variable for reading pin status*/ // Relay State bool toggleState_1 = LOW; //Define integer to remember the toggle state for relay 1 bool toggleState_2 = LOW; //Define integer to remember the toggle state for relay 2 bool toggleState_3 = LOW; //Define integer to remember the toggle state for relay 3 bool toggleState_4 = LOW; //Define integer to remember the toggle state for relay 4 // Switch State bool SwitchState_1 = LOW; bool SwitchState_2 = LOW; bool SwitchState_3 = LOW; bool SwitchState_4 = LOW; float temperature1 = 0; float humidity1 = 0; float ldrVal = 0; DHT dht(DHTPIN, DHT11); //For DHT 11 //DHT dht(DHTPIN, DHT22); //For DHT 22 SimpleTimer Timer; //The framework provides some standard device types like switch, lightbulb, fan, temperature sensor. static Switch my_switch1(deviceName_1, &amp;RelayPin1); static Switch my_switch2(deviceName_2, &amp;RelayPin2); static Switch my_switch3(deviceName_3, &amp;RelayPin3); static Switch my_switch4(deviceName_4, &amp;RelayPin4); static TemperatureSensor temperature(&quot;Temperature&quot;); static TemperatureSensor humidity(&quot;Humidity&quot;); static TemperatureSensor ldr(&quot;LDR&quot;); void sysProvEvent(arduino_event_t *sys_event) { switch (sys_event-&gt;event_id) { case ARDUINO_EVENT_PROV_START: #if CONFIG_IDF_TARGET_ESP32 Serial.printf(&quot;\nProvisioning Started with name \&quot;%s\&quot; and PoP \&quot;%s\&quot; on BLE\n&quot;, service_name, pop); printQR(service_name, pop, &quot;ble&quot;); #else Serial.printf(&quot;\nProvisioning Started with name \&quot;%s\&quot; and PoP \&quot;%s\&quot; on SoftAP\n&quot;, service_name, pop); printQR(service_name, pop, &quot;softap&quot;); #endif break; case ARDUINO_EVENT_WIFI_STA_CONNECTED: Serial.printf(&quot;\nConnected to Wi-Fi!\n&quot;); digitalWrite(wifiLed, true); break; } } void write_callback(Device *device, Param *param, const param_val_t val, void *priv_data, write_ctx_t *ctx) { const char *device_name = device-&gt;getDeviceName(); const char *param_name = param-&gt;getParamName(); if (strcmp(device_name, deviceName_1) == 0) { Serial.printf(&quot;Lightbulb = %s\n&quot;, val.val.b ? &quot;true&quot; : &quot;false&quot;); if (strcmp(param_name, &quot;Power&quot;) == 0) { Serial.printf(&quot;Received value = %s for %s - %s\n&quot;, val.val.b ? &quot;true&quot; : &quot;false&quot;, device_name, param_name); toggleState_1 = val.val.b; (toggleState_1 == false) ? digitalWrite(RelayPin1, HIGH) : digitalWrite(RelayPin1, LOW); param-&gt;updateAndReport(val); } } else if (strcmp(device_name, deviceName_2) == 0) { Serial.printf(&quot;Switch value = %s\n&quot;, val.val.b ? &quot;true&quot; : &quot;false&quot;); if (strcmp(param_name, &quot;Power&quot;) == 0) { Serial.printf(&quot;Received value = %s for %s - %s\n&quot;, val.val.b ? &quot;true&quot; : &quot;false&quot;, device_name, param_name); toggleState_2 = val.val.b; (toggleState_2 == false) ? digitalWrite(RelayPin2, HIGH) : digitalWrite(RelayPin2, LOW); param-&gt;updateAndReport(val); } } else if (strcmp(device_name, deviceName_3) == 0) { Serial.printf(&quot;Switch value = %s\n&quot;, val.val.b ? &quot;true&quot; : &quot;false&quot;); if (strcmp(param_name, &quot;Power&quot;) == 0) { Serial.printf(&quot;Received value = %s for %s - %s\n&quot;, val.val.b ? &quot;true&quot; : &quot;false&quot;, device_name, param_name); toggleState_3 = val.val.b; (toggleState_3 == false) ? digitalWrite(RelayPin3, HIGH) : digitalWrite(RelayPin3, LOW); param-&gt;updateAndReport(val); } } else if (strcmp(device_name, deviceName_4) == 0) { Serial.printf(&quot;Switch value = %s\n&quot;, val.val.b ? &quot;true&quot; : &quot;false&quot;); if (strcmp(param_name, &quot;Power&quot;) == 0) { Serial.printf(&quot;Received value = %s for %s - %s\n&quot;, val.val.b ? &quot;true&quot; : &quot;false&quot;, device_name, param_name); toggleState_4 = val.val.b; (toggleState_4 == false) ? digitalWrite(RelayPin4, HIGH) : digitalWrite(RelayPin4, LOW); param-&gt;updateAndReport(val); } } } void readSensor() { ldrVal = map(analogRead(LDR_PIN), 400, 4200, 0, 100); Serial.print(&quot;LDR - &quot;); Serial.println(ldrVal); float h = dht.readHumidity(); float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit if (isnan(h) || isnan(t)) { Serial.println(&quot;Failed to read from DHT sensor!&quot;); return; } else { humidity1 = h; temperature1 = t; Serial.print(&quot;Temperature - &quot;); Serial.println(t); Serial.print(&quot;Humidity - &quot;); Serial.println(h); } } void sendSensor() { readSensor(); temperature.updateAndReportParam(&quot;Temperature&quot;, temperature1); humidity.updateAndReportParam(&quot;Temperature&quot;, humidity1); ldr.updateAndReportParam(&quot;Temperature&quot;, ldrVal); } void manual_control() { if (digitalRead(SwitchPin1) == LOW &amp;&amp; SwitchState_1 == LOW) { digitalWrite(RelayPin1, LOW); toggleState_1 = 1; SwitchState_1 = HIGH; my_switch1.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, toggleState_1); Serial.println(&quot;Switch-1 on&quot;); } if (digitalRead(SwitchPin1) == HIGH &amp;&amp; SwitchState_1 == HIGH) { digitalWrite(RelayPin1, HIGH); toggleState_1 = 0; SwitchState_1 = LOW; my_switch1.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, toggleState_1); Serial.println(&quot;Switch-1 off&quot;); } if (digitalRead(SwitchPin2) == LOW &amp;&amp; SwitchState_2 == LOW) { digitalWrite(RelayPin2, LOW); toggleState_2 = 1; SwitchState_2 = HIGH; my_switch2.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, toggleState_2); Serial.println(&quot;Switch-2 on&quot;); } if (digitalRead(SwitchPin2) == HIGH &amp;&amp; SwitchState_2 == HIGH) { digitalWrite(RelayPin2, HIGH); toggleState_2 = 0; SwitchState_2 = LOW; my_switch2.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, toggleState_2); Serial.println(&quot;Switch-2 off&quot;); } if (digitalRead(SwitchPin3) == LOW &amp;&amp; SwitchState_3 == LOW) { digitalWrite(RelayPin3, LOW); toggleState_3 = 1; SwitchState_3 = HIGH; my_switch3.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, toggleState_3); Serial.println(&quot;Switch-3 on&quot;); } if (digitalRead(SwitchPin3) == HIGH &amp;&amp; SwitchState_3 == HIGH) { digitalWrite(RelayPin3, HIGH); toggleState_3 = 0; SwitchState_3 = LOW; my_switch3.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, toggleState_3); Serial.println(&quot;Switch-3 off&quot;); } if (digitalRead(SwitchPin4) == LOW &amp;&amp; SwitchState_4 == LOW) { digitalWrite(RelayPin4, LOW); toggleState_4 = 1; SwitchState_4 = HIGH; my_switch4.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, toggleState_4); Serial.println(&quot;Switch-4 on&quot;); } if (digitalRead(SwitchPin4) == HIGH &amp;&amp; SwitchState_4 == HIGH) { digitalWrite(RelayPin4, HIGH); toggleState_4 = 0; SwitchState_4 = LOW; my_switch4.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, toggleState_4); Serial.println(&quot;Switch-4 off&quot;); } } void setup() { Serial.begin(115200); // Set the Relays GPIOs as output mode pinMode(RelayPin1, OUTPUT); pinMode(RelayPin2, OUTPUT); pinMode(RelayPin3, OUTPUT); pinMode(RelayPin4, OUTPUT); pinMode(wifiLed, OUTPUT); // Configure the input GPIOs pinMode(SwitchPin1, INPUT_PULLUP); pinMode(SwitchPin2, INPUT_PULLUP); pinMode(SwitchPin3, INPUT_PULLUP); pinMode(SwitchPin4, INPUT_PULLUP); pinMode(gpio_reset, INPUT); // Write to the GPIOs the default state on booting digitalWrite(RelayPin1, !toggleState_1); digitalWrite(RelayPin2, !toggleState_2); digitalWrite(RelayPin3, !toggleState_3); digitalWrite(RelayPin4, !toggleState_4); digitalWrite(wifiLed, LOW); dht.begin(); // Enabling DHT sensor Node my_node; my_node = RMaker.initNode(nodeName); //Standard switch device my_switch1.addCb(write_callback); my_switch2.addCb(write_callback); my_switch3.addCb(write_callback); my_switch4.addCb(write_callback); //Add switch device to the node my_node.addDevice(my_switch1); my_node.addDevice(my_switch2); my_node.addDevice(my_switch3); my_node.addDevice(my_switch4); my_node.addDevice(temperature); my_node.addDevice(humidity); my_node.addDevice(ldr); Timer.setInterval(2000); //This is optional RMaker.enableOTA(OTA_USING_PARAMS); //If you want to enable scheduling, set time zone for your region using setTimeZone(). //The list of available values are provided here https://rainmaker.espressif.com/docs/time-service.html // RMaker.setTimeZone(&quot;Asia/Shanghai&quot;); // Alternatively, enable the Timezone service and let the phone apps set the appropriate timezone RMaker.enableTZService(); RMaker.enableSchedule(); //Service Name for (int i = 0; i &lt; 17; i = i + 8) { espChipId |= ((ESP.getEfuseMac() &gt;&gt; (40 - i)) &amp; 0xff) &lt;&lt; i; } Serial.printf(&quot;\nChip ID: %d Service Name: %s\n&quot;, espChipId, service_name); Serial.printf(&quot;\nStarting ESP-RainMaker\n&quot;); RMaker.start(); WiFi.onEvent(sysProvEvent); #if CONFIG_IDF_TARGET_ESP32 WiFiProv.beginProvision(WIFI_PROV_SCHEME_BLE, WIFI_PROV_SCHEME_HANDLER_FREE_BTDM, WIFI_PROV_SECURITY_1, pop, service_name); #else WiFiProv.beginProvision(WIFI_PROV_SCHEME_SOFTAP, WIFI_PROV_SCHEME_HANDLER_NONE, WIFI_PROV_SECURITY_1, pop, service_name); #endif my_switch1.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, false); my_switch2.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, false); my_switch3.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, false); my_switch4.updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, false); } void loop() { // Read GPIO0 (external button to reset device if (digitalRead(gpio_reset) == LOW) { //Push button pressed Serial.printf(&quot;Reset Button Pressed!\n&quot;); // Key debounce handling delay(100); int startTime = millis(); while (digitalRead(gpio_reset) == LOW) delay(50); int endTime = millis(); if ((endTime - startTime) &gt; 10000) { // If key pressed for more than 10secs, reset all Serial.printf(&quot;Reset to factory.\n&quot;); RMakerFactoryReset(2); } else if ((endTime - startTime) &gt; 3000) { Serial.printf(&quot;Reset Wi-Fi.\n&quot;); // If key pressed for more than 3secs, but less than 10, reset Wi-Fi RMakerWiFiReset(2); } } delay(100); if (WiFi.status() != WL_CONNECTED) { //Serial.println(&quot;WiFi Not Connected&quot;); digitalWrite(wifiLed, false); } else { //Serial.println(&quot;WiFi Connected&quot;); digitalWrite(wifiLed, true); if (Timer.isReady()) { //Serial.println(&quot;Sending Sensor Data&quot;); sendSensor(); Timer.reset(); // Reset a second timer } } manual_control(); } </code></pre> <p>ESP32 Board details here :</p> <p><a href="https://i.stack.imgur.com/P0l3A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P0l3A.png" alt="enter image description here" /></a></p>
<p>Maybe I've missed something, but the flash area is partitioned between usable app (roughly sketch code) space and usable filesystem space. I don't see any indication in your question that you're using a filesystem at all.</p> <p>Keeping your current settings except for switching the partition setting to <em>&quot;Huge APP (3MB No OTA/1MB SPIFFS)&quot;</em> resulted in:</p> <pre><code>Sketch uses 1790473 bytes (56%) of program storage space. Maximum is 3145728 bytes. Global variables use 53260 bytes (16%) of dynamic memory, leaving 274420 bytes for local variables. Maximum is 327680 bytes. </code></pre> <p>I'm not even sure &quot;Huge APP&quot; makes the <em>most</em> sense. Only that 3MB is larger than 1.2MB and larger than your current 1.8(ish)MB build apparently needs. It says &quot;no-OTA&quot; but you don't seem to be using that either. So, this seems like something you can do irrespective of whatever contributions you can trim from the text segment by tweaking your code.</p>
90926
|esp32|project|digitalwrite|digital-in|
Read Digital Input from Arduino Pin defined as OUTPUT
2022-10-04T12:38:37.507
<p>I'm working on a Home Automation Project. I can turn on-off ESP32 pin from Alexa and Google Assistant Successfully now.</p> <p>What I need help is with a way to read if the AC supply is ON/OFF on the Arduino pin. Or if possible to save pins I would want to read it on the same pin which id defined as Digital output to control the relay.</p> <p>Below attached image of what I have in mind.</p> <ol> <li>Normal switch turns On/off supply to load without any requirement of WiFi.</li> <li>Load is also connected to Relay NO, which is controlled by Arduino Pin D13.</li> </ol> <p>What I want is instead of just reading the status of the D13 pin, I want to read the status of the Mechanical Switch which directly provide to Load.</p> <p>So I'll actual status of the Load whether it's turned on by Switch or Relay with interrupting directly connected switch from load to supply.</p> <p><a href="https://i.stack.imgur.com/6jM9P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6jM9P.png" alt="enter image description here" /></a></p> <p>Edited: As others suggested it is not possible to use the Same Pin to control the relay and read AC load status. So is there a way to read the AC supply through the GPIO pin of ESP32 maintaining galvanic isolation, (opposite working of Relay)?</p>
<p>If you want to know the state of the load, I suggest to put the mechanical switch on the low-voltage side of the relay:</p> <p><img src="https://i.stack.imgur.com/4YR1F.png" alt="schematic" /></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f4YR1F.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>The voltage divider R<sub>1</sub>/R<sub>2</sub> is meant to lower the voltage at the transistor's collector (up to one diode threshold above Vcc) to a value suitable for the Arduino digital input.</p> <p>Note that you still need two separate inputs for controlling and for sensing the state.</p>
90940
|interrupt|pins|
Why doesn't my mcp23s17 interrupts work anymore?
2022-10-06T08:24:15.447
<p>I'm using a teensy 4.0 with two mcp23s17 gpio expanders where #1 has 16 buttons wired to it, and #2 has 4 buttons and six rotary encoders. To run everything I'm using majenkos mcp23s17 library. Recently, I refactored my code, and suddenly I'm unable to setup the mcp's to have interrupts working properly.</p> <p>I've tried to narrow the problem down by commenting out code, and it appears that as soon as I call <code>gpioExpander.enableInterrupt(pin, CHANGE);</code> in <code>gpioSetup()</code> the problem occurs. In detail, <code>loop()</code> runs fine, but as soon as I press a button, the teensy hangs. Also, to restore the teensy I have to upload the code with the call to <code>gpioExpander.enableInterrupt(pin, CHANGE);</code> commented out in order to have the teensy up and running again.</p> <p>I've been staring myself blind on the code, and I suspect I'm missing something obvious. Your help is appreciated.</p> <pre class="lang-cpp prettyprint-override"><code>//main.cpp #include &lt;Arduino.h&gt; #include &quot;GPIO.h&quot; #include &quot;MCP23S17.h&quot; extern MCP23S17 gpioExpander1; extern MCP23S17 gpioExpander2; void setup() { Serial.begin(115200); gpioSetup(); } void loop() { GPIOtest(gpioExpander1, gpioExpander2); } //GPIO.h #ifndef GPIO_H #define GPIO_H #include &lt;Arduino.h&gt; #include &quot;MCP23S17.h&quot; constexpr uint8_t address = 0; constexpr uint8_t interruptPin1 = 8; constexpr uint8_t interruptPin2 = 22; constexpr uint8_t chipSelectPin1 = 7; constexpr uint8_t chipSelectPin2 = 21; void setGPIO1Pins(MCP23S17 &amp;gpioExpander); void setGPIO2Pins(MCP23S17 &amp;gpioExpander); void gpioSetup(); void GPIO1interrupt(); void GPIO2interrupt(); void GPIOtest(MCP23S17 &amp;gpioExpander1, MCP23S17 &amp;gpioExpander2); #endif //GPIO.cpp #include &quot;GPIO.h&quot; #include &lt;Arduino.h&gt; #include &lt;MCP23S17.h&gt; volatile bool interruptFlag1 = false; volatile bool interruptFlag2 = false; MCP23S17 gpioExpander1(&amp;SPI, chipSelectPin1, address); MCP23S17 gpioExpander2(&amp;SPI, chipSelectPin2, address); // Set all Port Expander pins to desired mode INPUT_PULLUP // Set all Port Expander input pins interrupts void setGPIOPins(MCP23S17&amp; gpioExpander) { for (uint8_t pin = 0; pin &lt;= 15; ++pin) { gpioExpander.pinMode(pin, INPUT_PULLUP); gpioExpander.enableInterrupt(pin, CHANGE); } // set Port Expander Interrupt configuratons gpioExpander.setMirror(true); gpioExpander.setInterruptOD(false); gpioExpander.setInterruptLevel(LOW); } void gpioSetup() { gpioExpander1.begin(); gpioExpander2.begin(); digitalWrite(chipSelectPin1, HIGH); digitalWrite(chipSelectPin2, HIGH); pinMode(interruptPin1, INPUT_PULLUP); pinMode(interruptPin2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interruptPin1), GPIO1interrupt, LOW); attachInterrupt(digitalPinToInterrupt(interruptPin2), GPIO2interrupt, LOW); setGPIOPins(gpioExpander1); setGPIOPins(gpioExpander2); // GPIO registers are read to be cleared gpioExpander1.getInterruptValue(); gpioExpander2.getInterruptValue(); } void GPIO1interrupt() { interruptFlag1 = true; } void GPIO2interrupt() { interruptFlag2 = true; } void GPIOtest(MCP23S17&amp; gpioExpander1, MCP23S17&amp; gpioExpander2) { if (interruptFlag1 == true) { Serial.println(&quot;interrupt 1 = true&quot;); interruptFlag1 = false; } if (interruptFlag2 == true) { Serial.println(&quot;interrupt 2 = true&quot;); interruptFlag2 = false; } } </code></pre>
<h3>Short version, try:</h3> <pre class="lang-cpp prettyprint-override"><code>attachInterrupt(digitalPinToInterrupt(interruptPin1), GPIO1interrupt, FALLING); attachInterrupt(digitalPinToInterrupt(interruptPin2), GPIO2interrupt, FALLING); </code></pre> <p><strong><code>FALLING</code></strong> (instead of <code>LOW</code>) being the <a href="https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/" rel="nofollow noreferrer">active ingredient</a>. I'm assuming <code>FALLING</code> is supported. If not you can try synthesizing this with <code>CHANGE</code> and reading the port to see whether or not it is currently <code>LOW</code>.</p> <p>And then call <code>.getInterruptValue();</code> to clear the MCP23S17's interrupt condition where you clear the global volatile flags:</p> <pre class="lang-cpp prettyprint-override"><code>void GPIOtest(MCP23S17&amp; gpioExpander1, MCP23S17&amp; gpioExpander2) { if (interruptFlag1 == true) { Serial.println(&quot;interrupt 1 = true&quot;); interruptFlag1 = false; gpioExpander1.getInterruptValue(); // &lt;------ } if (interruptFlag2 == true) { Serial.println(&quot;interrupt 2 = true&quot;); interruptFlag2 = false; gpioExpander2.getInterruptValue(); // &lt;------ } } </code></pre> <hr /> <h3>Long version:</h3> <p>This a guess, since I'm unable to test. But this is maybe not a bad guess:</p> <p>You have configured the MCP23S17 device to <strong>drive</strong> active <strong>low</strong> on/during an MCP23S17 interrupt condition:</p> <pre class="lang-cpp prettyprint-override"><code> gpioExpander.setMirror(true); gpioExpander.setInterruptOD(false); gpioExpander.setInterruptLevel(LOW); </code></pre> <p>So, were an MCP23S17 interrupt to occur (<code>gpioExpander.enableInterrupt(pin, CHANGE);</code>), the interrupt flag within the MCP23S17 would be set, and INTA/INTB of the MCP23S17 would become active low.</p> <p>The MCP23S17 datasheet says:</p> <blockquote> <p>The interrupt condition is cleared after the LSb of the data is clocked out during a read command of GPIO or INTCAP</p> </blockquote> <p>You have configured your interrupt pins for interrupting on a LOW <strong>level</strong> interrupt:</p> <pre class="lang-cpp prettyprint-override"><code>attachInterrupt(digitalPinToInterrupt(interruptPin1), GPIO1interrupt, LOW); </code></pre> <p>So, if I understand this correctly, your Teensy continually re-enter the <code>GPIO#interrupt()</code> functions until something read causes the interrupt condition to be cleared. You are not clearing the interrupt condition <strong>inside</strong> the ISR, you're setting a flag to do that later in the main line of execution, which is reasonable by itself. One thing I can guess is that had you'd previous had something to clear the interrupt condition <strong>inside</strong> the interrupt and it is now outside the interrupt, namely your call to <code>.getInterruptValue()</code>, which <a href="https://github.com/MajenkoLibraries/MCP23S17/blob/6f6bac/src/MCP23S17.cpp#L503-L505" rel="nofollow noreferrer">reads the INTCAP register</a> mentioned above. Or perhaps you'd be using <a href="https://github.com/MajenkoLibraries/MCP23S17/blob/6f6bac/src/MCP23S17.cpp#L348-L352" rel="nofollow noreferrer">one of the functions</a> that reads a pin/port that would have cleared the interrupt condition. Clearing the global variable alone will not clear the interrupt condition, and so you're going to go right back into ISR which will reassign the global variable.</p> <p>An AVR will execute a single instruction outside of the ISR before reentering the ISR. So the effect of remaining in the interrupt condition is to make your code slow, potentially <strong>very</strong> slow. I don't know off the top of my head what the Teensy 4.x core will do in this case. Either way, it <em>would</em> lock up or possibly <em>look</em> locked up.</p> <p><em>If</em> you were reading/getting-interrupt-value inside the ISR it would have cleared it and so it would not re-entered the ISR repeatedly. Or rather, it wouldn't do that in definitely (or just for long). <em>It possible that the Teensy is so much faster that it might re-enter a few times until the MCP23S17 got around to acknowledging that the interrupt condition had be cleared. I'm not advocating for this so, so I'll leave it at that.</em></p> <p>I believe ultimately what you want is to set a <code>FALLING</code> edge interrupt:</p> <pre class="lang-cpp prettyprint-override"><code>attachInterrupt(digitalPinToInterrupt(interruptPin1), GPIO1interrupt, FALLING); </code></pre> <p>Anyway, with <code>FALLING</code> the initial falling edge of the INTA/INTB line sets the interrupt condition in the Teensy (not MCP23S17) but it is cleared when your ISR executes. So you will not keep re-entering the ISR. So your ISR will enter <em>once</em> to set the global <code>volatile</code> flag. Later when you pick up on the set value of your global <code>volatile</code> flag(s), you need to call <code>.getInterruptValue()</code> (or otherwise read a pin) to clear the interrupt condition in your MCP23S17 (not Teensy) which will de-assert/raise INTA/INTB, at which point the ISR in the Teensy is ready for to get trigger by another falling edge of INTA/INTB.</p> <p>It's also probably possible to do this with a <code>LOW</code>-level interrupt, but you'd have keep un-configuring them in the ISR and re-configuring them after you clear the MCP23S17's condition. Not sure that would be recommended. But, I think it's possible.</p>
90943
|button|stepper|
How to count steps of a stepper motor with AccelStepper?
2022-10-06T14:35:47.110
<p>I want to turn on my motor and count how many total rounds it has until my limit switch is switched on. After that, I want to count rounds counterclockwise until another limit switch is pushed. For this, I'm using <a href="https://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#aa4a6bdf99f698284faaeb5542b0b7514" rel="nofollow noreferrer">AccelStepper</a> and ezButton lib.</p> <p>Here is my code:</p> <pre><code> if ((limitSwitch_XV.getState() == LOW) &amp;&amp; (limitSwitch_XE.getState() == LOW) &amp;&amp; rightDirectionX) { while (1) { stepper1.step(-1); stageSizeX++; } } </code></pre> <p>But here I've got an error which says that I can't use <code>int</code> in <code>step()</code>: <code>'virtual void AccelStepper::step(long int)' is protected within this context stepper1.step(1);</code></p> <p>So how can I count the steps and go step by step to the given direction until I reach the limit switch with AccelStepper?</p>
<p>You get that error, because the <code>step()</code> method is protected in the AccelStepper class. It is not meant for calling by the user. AccelStepper instead wants you to state, what kind of movement you want (moving a specific distance/to a specific point/with a specific speed) and then frequently call the <code>AccelStepper.run()</code> method (or <code>AccelStepper.runSpeed()</code>), which will then execute the steps, when it is time to do so based on your planned movement.</p> <hr /> <p>If you want to solve your problem you have basically two ways to do this:</p> <ul> <li><p>With AccelStepper: Set the stepper to run at a specific speed in the correct direction, then in a loop calling <code>stepper1.runSpped()</code> and testing your limitswitch with <code>digitalRead()</code>. So something along the lines of:</p> <pre><code> stepper1.setCurrentPosition(0); stepper1.setSpeed(20); // Change speed according to your needs, negative values let the motor rotate in the other direction while(limitSwitch_XV.getState() == HIGH){ // Assuming, that limit switch is not pressed when HIGH stepper1.runSpeed(); } int revolutions = stepper1.currentPosition() / steps_per_revolution; </code></pre> </li> <li><p>or without AccelStepper: Depending on your stepper driver you can use a less sophisticated stepper library (like Arduinos <code>Stepper</code> library) or just control the stepper directly with <code>digitalWrite()</code> calls (to the Dir pin and to the Pulse pin). In that case you can do each step yourself, after each checking for the limit switch with <code>digitalRead()</code>. Something along the lines (I assume a stepper driver with dir pin and pulse pin, not one with multiple phase pins):</p> <pre><code> digitalWrite(dir_pin, direction); // provide HIGH or LOW here depending on wanted direction int pos = 0; while(limitSwitch_XV.getState() == HIGH){ digitalWrite(pulse_pin, HIGH); delayMicroseconds(10); digitalWrite(pulse_pin, LOW); pos++; delayMicroseconds(50); // Change this value according to the wanted speed } int revolutions = pos / steps_per_revolution; </code></pre> </li> </ul> <p>Note, that both code snippets are totally untested and you need to build the surrounding code yourself. They only highlight the principle.</p>
90953
|arduino-uno|
Can i use SCL, SDA pin for I2C
2022-10-07T20:01:25.750
<p>I read <a href="https://playground.arduino.cc/Main/I2CBi-directionalLevelShifter/" rel="nofollow noreferrer">this article</a>. In the article, it uses A4 and A5 for I2C. But can I just use SCL and SDA pin directly in the Arduino UNO R3? And do I need a put-up resistor for SCL and SDA pin?</p>
<p>Pins A4/A5 and the SCL/SDA pins are <em>the exact same pins</em> on the Arduino UNO R3. Not just &quot;they perform the same function&quot;, but they are physically the same pins. It is one solid piece of metal from one pin to the other.</p> <p>You don't <em>need</em> pullup resistors on the I2C pins because the <code>Wire</code> library turns on the internal pullups by default. However those internal pullups are about a tenth of the strength that I2C pullups <em>should</em> be, so I would recommend that you <em>do</em> add pullups, certainly for anything more than a couple of inches of wire.</p>
90964
|esp32|error|
ESP32 Rebooting while converting String to Hex Array
2022-10-08T19:18:44.893
<p>I wrote <a href="https://drive.google.com/file/d/12ImK6y2eZ9eO5znS2TJ3GHKRzaxjviwI/view?usp=sharing" rel="nofollow noreferrer">this</a> code to convert String to Hex Array.</p> <pre><code>const char* hexstring = &quot;0x21 0x73 0x10 0xfa 0x7a 0x00 0xff .../*40995 character long string*/....0xaa&quot; void setup() { char* temp; //Serial.printf(&quot;%s&quot;,hexstring); unsigned int number[8199]; number[0] = strtoul (hexstring,&amp;temp,16); for(int i=1;i&lt;8199;i++) number[i]= (int)strtoul(temp, &amp;temp, 16); for(int i=0;i&lt;8199;i++) { if(i%64) printf(&quot;\n&quot;); printf(&quot;%d, &quot;,number[i]); } } void loop(){ } </code></pre> <p>But it is causing ESP32 to reboot. <a href="https://i.stack.imgur.com/K03W3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K03W3.png" alt="enter image description here" /></a></p> <p>Could anyone help me with the reason why?</p>
<pre class="lang-cpp prettyprint-override"><code>void setup() { char* temp; //Serial.printf(&quot;%s&quot;,hexstring); unsigned int number[8199]; &lt;----- too much. </code></pre> <p>So, you're trying to put a 32796 byte object on the stack. I don't know exactly why you're seeing the manifestation that you are, but I'm not surprised.</p> <p>I just took an ESP32-CAM and started playing with different sizes and found that around 1800 (<code>unsigned int</code>s) is where things start to go sideways, failing occasionally rather than constantly. By a 2000 count, it continually reboots with <code>rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)</code> transitioning to <code>rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) </code> and later to very roughly around 5000 it becomes <code>rst:0x8 (TG1WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)</code></p> <p>I <em>may</em> fill out some details later if I look into it deeper. The ESP32 and SDK is complicated enough that there may well be a function can call that will permit a higher stack level. But this is mostly to satisfy curiosity.</p> <p>Putting very large things (relative to the system size) on the stack is usually not done. I hesitate to try to tell you what exactly you should do; it wouldn't surprise me if you don't need this array at all for what you ultimately want to do, but that's a <em>different</em> question). So, I'll just say get it off the stack through either dynamic memory allocation (e.g. through <code>new</code> or <code>malloc</code>), possibly using a smart pointer (e.g. <code>std::unique_ptr</code>) to manage that since those are available on the ESP32, or perhaps just making the variable either a <code>static</code> local or global. Or again if possible finding out why you might not need this array.</p> <h3>Simple minimal change</h3> <p>So, I'm not going to tell you that this is a good idea, but a minimal change would be to <code>static</code> qualify this as <code>static unsigned int number[8199];</code> Then you won't get that reset cause, here, for this reason.</p> <hr /> <h3>Some details for anyone curious</h3> <p>If you want to see some of the guts, you look in the ESP32 core for Arduino where it <a href="https://github.com/espressif/arduino-esp32/blob/2.0.5/cores/esp32/main.cpp#L71" rel="nofollow noreferrer">creates the task</a> that <a href="https://github.com/espressif/arduino-esp32/blob/2.0.5/cores/esp32/main.cpp#L42" rel="nofollow noreferrer">ultimately runs <code>setup()</code></a> for you. You can see that it calls <a href="https://github.com/espressif/arduino-esp32/blob/2.0.5/cores/esp32/main.cpp#L36-L38" rel="nofollow noreferrer"><code>getArduinoLoopTaskStackSize()</code></a> returning <a href="https://github.com/espressif/arduino-esp32/blob/2.0.5/cores/esp32/main.cpp#L14" rel="nofollow noreferrer"><code>ARDUINO_LOOP_STACK_SIZE</code></a> which by default is <code>8192</code>. 8192 <strong>bytes,</strong> not <code>unsigned int</code>s. With <code>sizeof(unsigned int)</code> being 4, this is <em>very roughly</em> in the vicinity of the 1800 <code>unsigned int</code>s where things started to fall apart in my testing above. Rather than chase down the configurion I just made a sketch that does <code>Serial.println(getArduinoLoopTaskStackSize());</code> and yeah, it prints 8192.</p> <p><code>getArduinoLoopTaskStackSize</code> is a <a href="https://en.wikipedia.org/wiki/Weak_symbol" rel="nofollow noreferrer">weakly defined</a> function which would allow something to redefine in elsewhere in the program to overload the default one. So, just out of curiosity I wrote one as follows:</p> <pre class="lang-cpp prettyprint-override"><code>size_t getArduinoLoopTaskStackSize(void) { size_t r_size = sizeof(unsigned int [8199]); // exactly the size your array r_size += r_size &gt;&gt; 3; // add about 1/8 (or 12.5%) extra return r_size; } </code></pre> <p>It no longer crashes. Should you do this? Probably not. But, if you ever have a legitimate reason to put a 32K array on the stack on an ESP32 it <em>may</em> be an option. I mostly just did this to see what would happen. It's barely been tested.</p>
90966
|arduino-mega|i2c|voltage|
Arduino outputting 4.7V instead of 3.3V when using I2C communication/sensor?
2022-10-08T23:56:09.157
<p>TOF050C-VL6180X Sensor was not responding, so I checked it with a multi-meter, and the VIN, GND solder pins on it read 4.7V. Double-checked Mega voltage, without anything connected, and it shows stable 3.6V. Connected a different ToF and it works perfectly, with a 3.6V on it.</p> <p>So that proves that sensor is damaged (might've powered it with 5V at first), but I don't understand how is it taking more than the regulated 3.3V? If it was shorted, it would read 0V, and if something burnt, it would be open circuit and show ~3.3V, right? So how is it just getting 4.7V out of nowhere? Any ideas on what I'm not understanding here?</p> <p>Thank you!</p> <p><strong>EDIT:</strong> More info, tried to isolate issue as much as I could</p> <p><strong>1)</strong> The non-working sensor shows 4.7V <a href="https://i.stack.imgur.com/DXhSZl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DXhSZl.jpg" alt="1) The non-working sensor shows 4.7V on multi-meter" /></a></p> <p><strong>2)</strong> The working sensor shows 3.4V and outputs distance to serial <a href="https://i.stack.imgur.com/qzoAHm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qzoAHm.jpg" alt="Working sensor shows 3.4V on multi-meter" /></a></p> <p><strong>3)</strong> This is where it gets weird. I uploaded the simple blink sketch and now the working sensor shows 4.7V too</p> <p><a href="https://i.stack.imgur.com/JpmM5m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JpmM5m.jpg" alt="Working sensor shows 4.7V on multi-meter" /></a></p> <p><strong>4)</strong> So I tried <strong>disconnecting the SDA/SCL</strong>, while leaving power connected, with the blink sketch running, and it's back to 3.3V!</p> <p><a href="https://i.stack.imgur.com/kwlBbm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kwlBbm.jpg" alt="Arduino outputs 3.3V to sensor" /></a></p> <p>**Tried the same steps with a different Mega, and <strong>it always shows 3.3V, no matter the configuration!</strong></p> <p>Now I'm very lost. So is the Arduino semi-damaged, with the I2C communication acting weird? Is it still safe to use with the project, if it <em>technically</em> works?</p>
<p>The Arduino Wire <a href="https://github.com/arduino/ArduinoCore-avr/blob/1.8.5/libraries/Wire/src/utility/twi.c#L87-L89" rel="nofollow noreferrer">enables the internal pullup resistor</a> on SDA and SDL. The internal pull-ups are specified at 20k to 50k. So you <em>are</em> providing 5V (or there about) to the sensor, though through a high resistance connection. So, the voltage isn't coming from nowhere.</p> <p>It is not unlikely that there protection/clamp diodes in the sensor IC or on the sensor board that connect these signals forward through the diode to the IC's 3.3v connection.</p> <p>So your SCL/SDA can be seen as very weakly (through roughly 35k) trying to backfeed your 3.3V regulator which is probably just blocking the current. If the sensor/board is using no current to speak of, either because it just doesn't normally or because it's dead, you would measure 5V minus a diode drop, or roughly the 4.7V you're seeing.</p> <p>If you assume the internal resistors are both at 20K as a &quot;worst&quot; case scenario for a calculation, the current needed through one to drop 5v to 3.3v is 85uA. So with 170uA load on the board that would drop the 3.3V pin connection back to its 3.3V level. About 170uA will flow through a 20k resistor with 3.3V across it. So if you want experiment take any resistor from about 470ohms all the way to just shy of 20k in parallel with your 3.3V / GND measurement and see if your 4.7V measurement doesn't drop right down to the normal 3.3V output.</p>
90971
|serial|can-bus|
VP230 CAN Bus Transceiver
2022-10-09T12:51:00.627
<p>How does one read can packets from a VP230 Can Bus transceiver? I also have a MCP2515 which I've gotten to work, but the VP230 is a lot smaller.</p> <p>I haven't been able to find any information about actually implementing the VP230, any help would be great.</p>
<p>Welcome. You are talking two compatible CAN parts but they have different functions. The VP230 is the CAN bus bidirectional interface. This converts the signals on the CAN bus to logic signals your CAN controller can use. The MPC2515 is a CAN controller chip that talks to your microprocessor and the bus transceiver. The MCP2515 has only logic signals and is not compatible with the CAN bus. Together they make a good CAN bus interface. Both parts are 3V3 compatible.</p>
90981
|esp32|data-type|
Conversion from `const char* datac="0x21,0x10,0xfa,0x7a,0xff";` to `uint8_t datat[]={0x21, 0x10, 0xfa, 0x7a, 0xff}`
2022-10-10T07:38:18.387
<p>The below reading data from API:</p> <pre><code>#include &lt;WiFi.h&gt; #include &lt;HTTPClient.h&gt; #include &lt;ArduinoJson.h&gt; const char* ssid = &quot;****&quot;; const char* pass = &quot;****&quot;; void setup() { Serial.begin(115200); WiFi.begin(ssid, pass); Serial.print(&quot;COnnecting&quot;); while (WiFi.status() != WL_CONNECTED) { Serial.print(&quot;.&quot;); delay(500); } Serial.print(&quot;\nIP Address&quot;); Serial.println(WiFi.localIP()); } void loop() { const char* root_0_id ; const char* root_0_Title ; if (WiFi.status() == WL_CONNECTED) { long rnd = random(1, 3); HTTPClient client; client.begin(&quot;https://6336d6c365d1e8ef267481aa.mockapi.io/api/bitmap/images?id=1&quot;); int httpCode = client.GET(); if (httpCode &gt; 0) { String payload = client.getString(); Serial.println(&quot;\nstatuscode: &quot; + String(httpCode)); if (payload == &quot;[]&quot;) Serial.println(&quot;\nNOT FOUND&quot;); else { DynamicJsonDocument doc(49152); DeserializationError error = deserializeJson(doc, payload); if (error) { Serial.print(&quot;deserializeJson() failed: &quot;); Serial.println(error.c_str()); return; } root_0_id = doc[0][&quot;id&quot;]; // &quot;41&quot; root_0_Title = doc[0][&quot;Bitmap&quot;]; Serial.print(&quot;\n\nData : &quot;); Serial.println(root_0_Title); Serial.println(sizeof(root_0_Title)); client.end(); dataReceived = 1; delay(10000); } } else { Serial.println(&quot;Error on HTTP request&quot;); } } } </code></pre> <p>I need help with parsing the <code>const char* root_0_Title=&quot;0x21,0x10,0xfa,0x7a,0xff&quot;</code>, to uint8_t[5]={0x21, 0x10, 0xfa, 0x7a, 0xff}?</p>
<p>you can use <a href="https://cplusplus.com/reference/cstring/strtok/" rel="nofollow noreferrer">strtok</a> (string tokenizer) and <a href="https://cplusplus.com/reference/cstdlib/strtol/" rel="nofollow noreferrer">strtol</a> (string to long) C functions.</p> <pre><code> int count = 0; uint8_t bytes[MAX_SIZE]; char* tok = strtok(root_0_Title, &quot;,&quot;); while (tok != NULL) { bytes[count++] = strtol(tok, NULL, 16); tok = strtok(NULL, &quot;,&quot;); } </code></pre>
90983
|arduino-nano|c++|led|
Function call only works if called once
2022-10-10T15:39:28.157
<p>I have 3 LED chains which are all mapped to concentric rings. Each ring has a its own 2D array with the chain number &amp; LED number. I have a function that is passed a ring array and then lights the appropriate LED. I'm using <code>FastLED</code></p> <pre><code>void lightUp(int ring_arr[][2], int i, int col){ if(ring_arr[i][0] == 0){ L0[ring_arr[i][1]] = CHSV(col, 255, 255); } if(ring_arr[i][0] == 1){ L1[ring_arr[i][1]] = CHSV(col, 255, 255); } if(ring_arr[i][0] == 2){ L2[ring_arr[i][1]] = CHSV(col, 255, 255); } } </code></pre> <p>This works fine BUT only if its called once in <code>loop()</code> if I make a 2nd call none of the LEDs light up. So I can light up 1 ring at a time but if I try to light up 2 or more then nothing lights up. Anyone see anything obvious that I'm overlooking?</p> <p>The full code listing,</p> <pre><code>#include &lt;FastLED.h&gt; #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) #define DATA_0 5 #define DATA_1 6 #define DATA_2 7 #define NUM_LEDS 50 CRGB L0[NUM_LEDS]; CRGB L1[NUM_LEDS]; CRGB L2[NUM_LEDS]; // Rings int ring_1[][2] = {{0,0}, {0,1}, {0,2}, {0,3}, {1,49}, {1,28}, {1,29}, {1,30}, {1,31}, {1,32}, {1,23}, {1,24}, {1,25}, {1,26}, {1,27}, {1,2}, {1,3}, {1,4}, {1,5}, {1,6}, {1,0}, {1,1}, {2,0}, {2,1}, {2,2}, {2,19}, {2,20}, {2,21}, {2,22}, {2,23}, {2,24}, {2,25}, {2,26}, {2,27}, {2,28}, {2,45}, {2,46}, {2,47}, {2,48}, {2,49}, {0,29}, {0,28}, {0,27}, {0,26}, {0,25}, {0,4}, {0,5}, {0,6}, {0,7}, {0,8}}; int ring_2[][2] = {{1,48}, {1,33}, {1,22}, {1,7}, {2,3}, {2,18}, {2,29}, {2,44}, {0,24}, {0,9}}; int ring_3[][2] = {{1,47}, {1,34}, {1,21}, {1,8}, {2,4}, {2,17}, {2,30}, {2,43}, {0,23}, {0,10}}; int ring_4[][2] = {{1,46}, {1,35}, {1,20}, {1,9}, {2,5}, {2,16}, {2,31}, {2,42}, {0,22}, {0,11}}; int ring_5[][2] = {{1,45}, {1,36}, {1,19}, {1,10}, {2,6}, {2,15}, {2,32}, {2,41}, {0,21}, {0,12}}; int ring_6[][2] = {{1,44}, {1,37}, {1,18}, {1,11}, {2,7}, {2,14}, {2,33}, {2,40}, {0,20}, {0,13}}; int ring_7[][2] = {{1,43}, {1,38}, {1,17}, {1,12}, {2,8}, {2,13}, {2,34}, {2,39}, {0,19}, {0,14}}; int ring_8[][2] = {{1,42}, {1,39}, {1,16}, {1,13}, {2,9}, {2,12}, {2,35}, {2,38}, {0,18}, {0,15}}; int ring_9[][2] = {{1,41}, {1,40}, {1,15}, {1,14}, {2,10}, {2,11}, {2,36}, {2,37}, {0,17}, {0,16}}; // Colours int col_1 = 0; int col_2 = 160; int col_3 = 96; void setup(){ // LED set up FastLED.addLeds&lt;WS2811,DATA_0,RGB&gt;(L0, NUM_LEDS); FastLED.addLeds&lt;WS2811,DATA_1,RGB&gt;(L1, NUM_LEDS); FastLED.addLeds&lt;WS2811,DATA_2,RGB&gt;(L2, NUM_LEDS); FastLED.setBrightness(255); clearAll(); } void loop() { for(int i; i &lt; NELEMS(ring_1); i++){ lightUp(ring_1, i, col_1); } for(int i; i &lt; NELEMS(ring_2); i++){ // lightUp(ring_2, i, col_2); // if I uncomment any of these // lightUp(ring_3, i, col_3); // no LEDs light up // lightUp(ring_4, i, col_1); // lightUp(ring_5, i, col_2); // lightUp(ring_6, i, col_3); // lightUp(ring_7, i, col_1); // lightUp(ring_8, i, col_2); // lightUp(ring_9, i, col_3); } FastLED.show(); delay(1000); } void clearAll(){ for(int i; i &lt; NUM_LEDS; i++){ L0[i] = CHSV(0, 0, 0); L1[i] = CHSV(0, 0, 0); L2[i] = CHSV(0, 0, 0); } FastLED.show(); } void lightUp(int ring_arr[][2], int i, int col){ if(ring_arr[i][0] == 0){ L0[ring_arr[i][1]] = CHSV(col, 255, 255); } if(ring_arr[i][0] == 1){ L1[ring_arr[i][1]] = CHSV(col, 255, 255); } if(ring_arr[i][0] == 2){ L2[ring_arr[i][1]] = CHSV(col, 255, 255); } } </code></pre>
<p>Your <code>for</code> loops are missing an initialization. You should write</p> <pre class="lang-cpp prettyprint-override"><code>for (int i = 0; i &lt; NELEMS(ring_1); i++) </code></pre> <p>but you missed the <code>= 0</code> part. This means the <code>i</code> variable ends up uninitialized, and contains whatever was left in this memory location by whatever used that memory before. The behavior in such situation is generally unpredictable. However, one may guess that the <code>i</code> of the second loop could be allocated in the same spot as the <code>i</code> of the first loop. If this happens, then the second loop starts at <code>i=3</code> and ends up being an empty loop.</p> <p>As a (completely unrelated) side note, you could gather your three <code>L*</code> arrays into a single 2D array. This would make <code>lightUp()</code> significantly simpler:</p> <pre class="lang-cpp prettyprint-override"><code>void lightUp(int ring_arr[][2], int i, int col) { L[ring_arr[i][0]][ring_arr[i][1]] = CHSV(col, 255, 255); } </code></pre> <p>or maybe it would be clearer like this:</p> <pre class="lang-cpp prettyprint-override"><code>void lightUp(int *location, int col) { L[location[0]][location[1]] = CHSV(col, 255, 255); } </code></pre> <p>To be called as <code>lightUp(ring_1[i], col_1);</code>.</p>
90984
|arduino-uno|shift-register|led-matrix|
Shiftout only handles one shift register at a time
2022-10-10T16:48:12.227
<p>I am making a 7x10 led matrix and I am having problems with the shiftout function. It is only able to show me the output in one shiftout register at a time. How can I fix it? <a href="https://i.stack.imgur.com/uxGrU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uxGrU.png" alt="enter image description here" /></a></p> <p>For example:</p> <pre><code>void setup(){ // PORTB as output. // Pin 13: Clock 74HC595 // Pin 12: Latch // Pin 11: Data // Pin 10: Reset // Pin 9: Clock CD4017 DDRB = 0b111111; // Makes sure the 4017 value is 0. PORTB = 0b100; delayMicroseconds(5); PORTB = 0; } void loop(){ shiftOut(11, 13, LSBFIRST, 0b1000111101); PORTB = 0b10000; delayMicroseconds(800); PORTB = 0; delay(10000); } </code></pre> <p>This is the output it produces:</p> <p><a href="https://i.stack.imgur.com/9AXCu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9AXCu.png" alt="enter image description here" /></a></p> <p>But with numbers of 8 bits or less the output is displayed correctly.</p> <p>shiftOut(11, 13, LSBFIRST, 0b10001111); <a href="https://i.stack.imgur.com/DBcas.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DBcas.png" alt="enter image description here" /></a></p>
<p><code>shiftOut</code> works on bytes. To do more than one byte you have to do more than one <code>shiftOut</code>. Also you have to take note of the bit ordering. You should shift the most significant bit first, not the least.</p> <p>For example, this:</p> <pre class="lang-cpp prettyprint-override"><code> shiftOut(11, 13, LSBFIRST, 0b1000111101); </code></pre> <p>should be:</p> <pre class="lang-cpp prettyprint-override"><code> shiftOut(11, 13, MSBFIRST, 0b10); shiftOut(11, 13, MSBFIRST, 0b00111101); </code></pre>
90988
|arduino-uno|programming|potentiometer|mosfet|speed|
How do I control the speed of a 2-wire fan with an Arduino and only a potentiometer?
2022-10-10T21:03:47.567
<p>I am trying to vary the speed of a 2-wire fan by using a Arduino Uno and only a potentiometer.</p> <p>Initially, I assumed that I could go about doing so by using a code that I used for dimming an LED. When I have run the code and varied the potentiometer, the LED on the power supply changed but, the fan did not come on. I assume that this was due to an error in the first code.</p> <p>In the second code, the fan also did not come on. I am unsure if it was my wiring. I have an voltage supply connected to a breadboard to power the fan.</p> <p>Additionally, would I require a mosfet or transistor despite using a potentiometer? This could have also be the problem regarding my second attempt.</p> <p><strong>First Code Attempt:</strong></p> <pre><code>int potPin=A2; int gPin=9; int potVal; float LEDVal; int dt=250; void setup() { // put your setup code here, to run once: pinMode(potPin, INPUT); pinMode(gPin, OUTPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: potVal=analogRead(potPin); LEDVal=(255./1023.)*potVal; analogWrite(gPin,LEDVal); Serial.println(LEDVal); delay(dt); } </code></pre> <p><strong>Second Code:</strong></p> <pre><code>int reading; int value; void setup() { pinMode(CONTROL, OUTPUT); } void loop() { reading = analogRead(POTENTIOMETER); value = map(reading, 0, 1024, 0, 255); analogWrite(CONTROL, value); }``` </code></pre>
<p>Like people have already mentioned in the comments, you likely need to add a FET to drive the fan. The Arduino simply can't put provide the current required to drive the fan. According to the Arduino documentation, the microcontroller can only provide 20mA per output pin, which is enough to drive LEDs but not fan motors.</p> <p>Luckily, there is a tutorial on the Arduino website for driving motors with PWM through a FET.<br /> <a href="https://docs.arduino.cc/learn/electronics/transistor-motor-control" rel="nofollow noreferrer">https://docs.arduino.cc/learn/electronics/transistor-motor-control</a></p> <p>The following program is adapted from the <a href="https://docs.arduino.cc/built-in-examples/analog/AnalogInOutSerial" rel="nofollow noreferrer">&quot;Analog In, Out Serial&quot; built-in example</a> and should be sufficient to control the speed of the motor.</p> <pre class="lang-C++ prettyprint-override"><code>// These constants won't change. They're used to give names to the pins used: const int analogInPin = A0; // Analog input pin that the potentiometer is attached to const int analogOutPin = 9; // Analog output pin that the FET is attached to int sensorValue = 0; // value read from the pot int outputValue = 0; // value output to the PWM (analog out) void setup() { // declare the ledPin as an OUTPUT: pinMode(analogOutPin, OUTPUT); } void loop() { // read the analog in value: sensorValue = analogRead(analogInPin); // map it to the range of the analog out: outputValue = map(sensorValue, 0, 1023, 0, 255); // change the analog out value: analogWrite(analogOutPin, outputValue); // wait 2 milliseconds before the next loop for the analog-to-digital // converter to settle after the last reading: delay(2); } </code></pre> <p>This program has not been tested and is intended as an example. Make sure that the output for the FET is wired to a pin that can output PWM. Then make sure that your program is referencing the correct pin.</p> <p>Make sure that your power supply has enough power to control the fan motor as well.</p> <p>Here are some wiring diagrams from the tutorial webpage.</p> <p><a href="https://i.stack.imgur.com/tve31.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tve31.png" alt="Transistor Motor Control Diagram" /></a> <a href="https://i.stack.imgur.com/3WuXI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3WuXI.png" alt="Transistor Motor Schematic" /></a></p> <p>Note: The particular fan that you are using might not be able to be driven by PWM and you should seek out and read the relevant documentation for the fan.</p>
91000
|esp8266|
ESP_ATMod and its many library dependencies
2022-10-11T19:22:11.373
<p>I'm trying to install <a href="https://github.com/JiriBilek/ESP_ATMod" rel="nofollow noreferrer">https://github.com/JiriBilek/ESP_ATMod</a> onto an ESP8266. The sketch has Includes to many libraries. Those libraries have includes to other libraries and so on. Do I have to manually follow all these dependencies and download them to compile and upload my sketch? Or is there an easier way.</p>
<p>An Arduino sketch is a folder not a file. The ESP_ATMod sketch has 11 files:</p> <pre><code>asnDecode.cpp asnDecode.h command.cpp command.h debug.h ESP_ATMod.h ESP_ATMod.ino settings.cpp settings.h WifiEvents.cpp WifiEvents.h </code></pre> <p>The sketch doesn't include libraries which would require installation. It uses only libraries bundled with the esp8266 platform: EEPROM, ESP8266mDNS, ESP8266WiFi and LittleFS. You don't have to install any libraries.</p> <p>You can download all the files at once with &quot;Download ZIP&quot;:</p> <p><a href="https://i.stack.imgur.com/848p0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/848p0.png" alt="enter image description here" /></a></p>
91003
|arduino-uno|display|
Display issues with 4 Digit, 14 segment
2022-10-12T03:04:46.687
<p>I have this HT16K33 4 Digit 14-segment display I got brand new. I connected it to my Arduino UNO, wired it up and uploaded some quick test code. However, the display looks completely broken (see image below), only some segments turn on.</p> <p><a href="https://i.stack.imgur.com/ylxVf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ylxVf.jpg" alt="broken display" /></a></p> <p>I soldered the connection pins to the HT16K33 board (see picture below). My solder isn't the best but it also shouldn't be too bad.</p> <p><a href="https://i.stack.imgur.com/ECc5T.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ECc5T.jpg" alt="Solder" /></a></p> <p>I did a quick resistance check on the connection pins to see if the pins were soldered correctly, and they seemed good. I'm not too sure how to test the ji2c pin though...</p> <p><a href="https://i.stack.imgur.com/wYMke.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wYMke.jpg" alt="multimeter_test" /></a></p> <p>Here is the Wiring on my breadboard:</p> <p><a href="https://i.stack.imgur.com/Qmdv8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qmdv8.jpg" alt="Wiring" /></a></p> <p>Finally here is the code i'm currently using:</p> <pre><code>#include &quot;HT16K33.h&quot; #include &lt;Wire.h&gt; HT16K33 seg(0x070); void setup() { // put your setup code here, to run once: Serial.begin(9600); Wire.begin(); if(!seg.begin()){ Serial.println(&quot;ERROR&quot;); while(1); } Wire.setClock(100000); Serial.println(&quot;displayTest()&quot;); seg.displayOff(); delay(1000); seg.displayOn(); seg.displayClear(); seg.displayInt(5); } void loop() { // put your main code here, to run repeatedly: } </code></pre> <p>I'm a bit troubled here and confused at what's going on... Help would be greatly appreciated</p>
<p>so @6v6gt's comment made me re-search for a library for a 14-segment HT16K33. It seems he/she was in the money since it started working after switching library. While I couldn't find any yesterday, I found this page today which covers 7-segment and 14-segment HT16K33: <a href="https://learn.adafruit.com/adafruit-led-backpack/0-54-alphanumeric?view=all#library-reference-3052482" rel="nofollow noreferrer">https://learn.adafruit.com/adafruit-led-backpack/0-54-alphanumeric?view=all#library-reference-3052482</a></p> <p>So I switched from the HT16K33 library to the &quot;Adafruit_LEDBackpack&quot; and &quot;Adafruit_GFX&quot; Libraries.</p> <p><a href="https://i.stack.imgur.com/ussgN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ussgN.jpg" alt="leds working" /></a></p> <p>Code for those wondering:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_GFX.h&gt; #include &quot;Adafruit_LEDBackpack.h&quot; Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4(); void setup() { Serial.begin(9600); alpha4.begin(0x70); // pass in the address alpha4.writeDigitAscii(0, 'A'); alpha4.writeDigitAscii(1, 'B'); alpha4.writeDigitAscii(2, 'C'); alpha4.writeDigitAscii(3, 'D'); alpha4.writeDisplay(); } void loop() { } </code></pre> <p>One question I have is (which is an entirely different subject), how do I go from here to rotate the letters and alphabet 180 degrees?</p>
91023
|arduino-mega|analogread|button|resistor|
Arduino Mega, 6 push buttons for each analog input (A0-A9) - closing one results in reading by other
2022-10-14T18:33:42.283
<p>On day to day basis I'm more of a high level programmer, with little electronics knowledge, apologies in advance if I lack some nomenclature or basics. I communicate with my Arduino Mega via firmata, so won't really bother with code as I believe my issue is 100% hardware issue (if proven wrong I'll share details surely)</p> <p>I'm creating a 'keyboard' with 60 arcade style push buttons (2pin), and I distinguish them by different resistance when circuit closes with A0-A9 (10 analog pins, 6 buttons each), and I need the rest of the pins for other functionalities.</p> <p>I've created a circuit similar to this fritzting schema: <a href="https://i.stack.imgur.com/2p9W2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2p9W2.jpg" alt="enter image description here" /></a></p> <p>So my issue is: when press button A0/button 1, pins A1 &amp; A2 also read the same value. If I press A0/button 2, I get a different value and can determine which button in A0 was pressed, but again - A1 &amp; A2 also read this, even though I didn't press them.</p> <p>I suspect I might've taken a different approach or even out of the box &quot;keyboard&quot; chips, but this is the route I've taken.</p> <p><a href="https://i.stack.imgur.com/5i4SO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5i4SO.jpg" alt="enter image description here" /></a></p> <p>How do I make it so when I press A0/button 1, A1/A2 doesn't read the value? Do I need separate V5? Or I simply need to put the wires differently somehow?</p> <p>Update: as per <strong>chrisl</strong> comment</p> <p>I've updated the circuit by adding a resistor for each button group:</p> <p><a href="https://i.stack.imgur.com/iYPke.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iYPke.jpg" alt="enter image description here" /></a></p> <p>And that has solved my issue.</p>
<p>Of course all three analog inputs show the same value. You have literally connected them to each other. Each green wire is connected to a red wire, which leads to the resistor at the bottom. Thus all three inputs are tied together.</p> <p>You can fix this by using one bottom resistor for each group of 2 buttons, each connected between 5V and the analog input/button system.</p> <p>And when using analog inputs for multiple buttons the binary resistor latter is an interesting concept, which might give you more buttons per analog input (depending on the noise in your environment). Though the typical way to read so many buttons would be using an additional chip/microcontroller to scan the buttons in a matrix style arrangement. With your current circuit you still need 30 analog inputs.</p>
91031
|arduino-nano|sensors|power|
Lag in sensor reading when Arduino Powered with 12V adaptor
2022-10-15T14:13:58.740
<p>So I am trying to power an arduino to measure water flow. It works all fine and dandy when I am powering it with laptop, but when I directly power it with 12V 1.5A adaptor the readings take a second to come to the LCD even though the pump starts running. Also when they come, I can see that sometimes it hangs. Why is that?</p> <p>Before taking the readings I am switching on a motor which is also directly powered by the adaptor just like the arduino.</p> <p>Below is a block diagram.</p> <p><a href="https://i.stack.imgur.com/uNCsp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uNCsp.png" alt="enter image description here" /></a></p> <p>Would adding a voltage regulator that steps down 12V to 9v between arduino and adaptor help?</p>
<p>Welcome. Your pump is turning on as soon as the power is turned on because the relay is connected to 5V. Your processor needs to initialize itself and then the display, the pump is up and running. On your laptop the pump was powered from the power supply and the Arduino by the laptop. The arduino was on and up and running when the pump was started. Hope this helps. I will take a SWAG and say this is powered up when the pump is needed and powered down when it is not needed.</p>
91036
|arduino-uno|arduino-ide|arduino-nano|
Library files multiple users
2022-10-15T20:38:20.323
<p>I want to place all of my libraries on the server. Currently the sketches work fine and as far as I know the libraries are coming from the individual linux mint machines using cinnamon, releases vary depending on machine. I can move the libraries etc but what do I do to the IDE 1.8.18 and 1.8.19? to make it follow that path.</p>
<p>Arduino IDE can use libraries only from 3 locations.</p> <ol> <li>libraries folder in sketchbook folder</li> <li>libraries folder of selected board's platform</li> <li>libraries folder in IDE installation folder (only IDE 1, not IDE 2)</li> </ol> <p>There is no option to configure other paths and absolute or relative paths don't work in <code>#include</code> directive with the Arduino build process.</p> <p>The only way to use libraries from a different location is to link with means of the operating system the folder with the library into one of the searched locations.</p>
91054
|c++|atmega328|timers|rtc|
1Hz & 32Hz from 32.768 kHz on ATmega328P at 8MHz & DS3231 32K
2022-10-17T15:57:09.357
<p>I have a 32.768 kHz signal at the ATmega328P input. I need to get 2 signals from this signal: 1Hz and 32Hz. How well will it work? How to do this with a ATmega328P Timer/Counter? What gain will the Timer/Counter give compared to my solution?</p> <pre><code>void setup() { pinMode(S32768Hz_PIN, INPUT_PULLUP); // 32.768 kHz signal attachInterrupt(digitalPinToInterrupt(S32768Hz_PIN), s32768Isr, FALLING); // Pin 3 } volatile bool s32768IsrWasCalled = false; // ISR flag 32768Hz void s32768Isr() { s32768IsrWasCalled = true; } uint16_t s32Counter = 0; uint16_t s1Counter = 0; void loop() { if (s32768IsrWasCalled) { s32768IsrWasCalled = false; s32Counter++; if (s32Counter == 1024) { s32Counter = 0; // 32Hz } s1Counter++; if (s1Counter == 32768) { s1Counter = 0; // 1Hz } } } </code></pre> <p>Update 24.10.2022 I wrote my first timer 1 setup code. Will this run 32 times per second, indefinitely?</p> <pre><code>// ATmega328P 3.3V 8MHz, Timer 1 &amp; DS3231 32768 Hz void setupTimer1() { // Disables all interrupts cli(); // Reset bits TCCR1A = 0; TCCR1B = 0; // Enable Timer 1 overflow interrupt (TOIE1) TIMSK1 = (1 &lt;&lt; TOIE1); // PWM mode. Mode #7 (fast PWM, top is fixed at 10 bits = 1024) TCCR1A |= _BV(WGM10) | _BV(WGM11); TCCR1B |= _BV(WGM12); // External clock on T1 pin, on falling edge (DS3231 32768Hz pin) TCCR1B |= (1 &lt;&lt; CS11) | (1 &lt;&lt; CS12); // Enables interrupts sei(); // pinMode(T1_pin, INPUT_PULLUP); ? } void loop() { // So get 1 Hz from 32 Hz? // There will be no data races here? if((pulse_counter % 32) == 0) { callback1Hz(); } if((pulse_counter % 2) == 0) { callback16Hz(); } } volatile uint8_t pulse_counter; // Timer 1 Overflow (32 Hz) ISR(TIMER1_OVF_vect) { pulse_counter++; } </code></pre> <p>Thank you!</p>
<p>I did not test your program but, just by looking at it, I would expect it to work... provided you do not add more code! Obviously you will need to add more code in order to do something useful with those signals, and then thinks might break.</p> <p>The problem with this approach is that the interrupt rate is pretty high: the program gets interrupted every 30.5 µs. You may miss an interrupt if either:</p> <ol> <li><p>it fires while there is already an interrupt (or other critical section) being processed, and that interrupt (maybe combined with some other pending interrupt) takes more than 30.5 µs to complete</p> </li> <li><p>you add more code to <code>loop()</code> and that function ends up taking more than 30.5 µs.</p> </li> </ol> <p>The first condition should be obvious, but I would assume the risk is quite low, as only a very poorly written ISR would take that long to complete. Beware however of library code, as that might bring surprises.</p> <p>The second condition is a bigger risk, although maybe less obvious. The problem is that this <code>loop()</code> assumes the code within <code>if (s32768IsrWasCalled)</code> is going to be called exactly once per interrupt. This may not be the case: if the program gets bigger, you may miss interrupts, and get the frequencies wrong.</p> <p>A simple way to avoid the issue number 2 is to count the pulses within the ISR, as PMF suggests in a comment. I would use a single counter for this, and make it unsigned in order to guarantee that it wraps around reliably:</p> <pre class="lang-cpp prettyprint-override"><code>volatile uint16_t pulse_counter; void s32768Isr() { pulse_counter++; } void loop() { int signal_32Hz = (pulse_counter &gt;&gt; 9) &amp; 1; int signal_1Hz = (pulse_counter &gt;&gt; 14) &amp; 1; } </code></pre> <p>Note that this is one of the few cases when you can access the volatile multi-byte variable without disabling interrupts: since you only ever care about one bit, there is no data race.</p> <p>A better option, though, would be to use a hardware timer for this job. I would suggest using Timer 1 in “counter” mode (external clock source on pin T1). Using mode 7 (fast PWM, 10-bit) you get the 32 Hz signal entirely generated by the hardware. And then you can use the timer overflow interrupt to generate 1 Hz. The interrupt rate is now 1024 times lower. I let you check the datasheet for the details.</p>
91072
|esp8266|temperature-sensor|
Temperature sensors are heating themselves
2022-10-19T08:38:10.130
<p>I have 2 IoT devices for measuring room temperature. Room does not have direct sunlight (it is north oriented and have tree in front of window). One is ESP8266 with DHT11 and next one is ESP8266 with DS18B20. DHT is on the table, away from PC. DS18B20 is on the top of bookshelf next to plant. Both of them shows temperature around 32-33 deg. celsius. It is not that hot in the room for sure. My home thermostat shows 23-24 deg. celsius. Outside temperature is about 15 deg. When I open the window and cool down the room, I can see temerature drop on both sensors, but still ony to around 26-28 celsius. I think, they are overheating themselves.</p> <p>Code is almost same on both devices. Sampling every minute, so it should not be an issue of overloading sensors. Supply voltage is 3,3V. Not parasitic with 2k2 pull-up resistor.</p> <p>What should I do to get correct temperature reading from these sensors?</p> <p>EDIT: I have tired to get sensor out of PCB. First, I have just raised it for lengt of its legs (about 1cm) above board. It helped little, but it is visible, that sensor started cold, and slowly saturated heat from wires. So I took quite thick cables (0,25mm^2) and put sensor about 10cm away from board. And it helped! Temperature is about 23 degrees, what is somwhere in expected range. Most important is, that temperature curve was dropping before stabilizing. Spikes are just 85°C first reading. <a href="https://i.stack.imgur.com/oKag6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oKag6.png" alt="enter image description here" /></a></p>
<p>It seems, that problem is in heat transfer from ESP chip to thermometer via wires. Worst it was, when chip was on board itself, little bit better when it was raised about 1cm out of board. I have achieved correct readings only when I put sensor on longer and quite thick leads to avoid heat transfer as much as possible.</p>
91074
|arduino-ide|c++|atmega328|class|callbacks|
Call functions of one class from another class - Callback
2022-10-19T14:46:55.933
<p>I am new to C++ &amp; I need to call functions of one class from another class. And so that the classes do not know anything about each other. How to do it in Arduino environment?</p> <pre><code>class Encoder { using CallBack2 = void( * )(const int, const int); using CallBack0 = void( * )(); private: CallBack2 callbackUpDown; CallBack0 callbackTab; CallBack0 callbackLongPress; public: Encoder() {} void Setup(CallBack2 updown, CallBack0 tab, CallBack0 cbLongPress) { callbackUpDown = updown; callbackTab = tab; callbackLongPress = cbLongPress; } void Loop() { if (true) { callbackUpDown(-1, 300); callbackTab(); callbackLongPress(); } } }; class Menu { public: void UpDown(const int direction, const int count) {} void Tab() {} }; class RTC { public: void Setup() {} void Toggle() {} }; class Display { public: void Toggle() {} }; Encoder encoder = Encoder(); RTC rtc = RTC(); Menu menu = Menu(); Display display = Display(); void setup() { rtc.Setup(); encoder.Setup(menu.UpDown, menu.Tab, []{display.Toggle();rtc.Toggle();}); } void loop() { encoder.Loop(); } </code></pre> <p>Output:</p> <pre><code>In file included from sun.ino:47:0: callback.h: In function 'void setup()': callback.h:52:75: error: invalid use of non-static member function 'void Menu::UpDown(int, int)' encoder.Setup(menu.UpDown, menu.Tab, []{display.Toggle(); rtc.Toggle();}); ^ callback.h:28:7: note: declared here void UpDown(const int direction, const int count) {} ^~~~~~ </code></pre> <p>Thank you!</p>
<p>Also, <a href="https://blog.mbedded.ninja/programming/languages/c-plus-plus/callbacks/" rel="nofollow noreferrer">Using Static Methods Or Non-Member Functions (C-Style)</a></p> <pre><code>class MyClass { public: static void onMsg(int num1, int num2) { // NOTE: Can't call any non-static method functions here! } }; class LibraryClass { using CallBack = void( * )(int, int); private: CallBack callBack; public: void Setup(CallBack callBackFunc) { callBack = callBackFunc; } void Loop() { callBack(1, 2); } }; MyClass myClass; LibraryClass libraryClass; void setup() { libraryClass.Setup(&amp;myClass.onMsg); // Provide the instance and function to call } void loop() { libraryClass.Loop(); } </code></pre>
91075
|serial|sensors|
How real-time is an arduino (react to sensor)?
2022-10-19T15:24:45.297
<p>New to arduino here, sorry for asking what may be a trivial question.</p> <p>I need to simulate an industrial machine at home. It operates in a cyclic motion, creating an event for every rotation / cycle. Imagine a turntable or wheel with a marker in one place.</p> <p>What I would like is:</p> <ul> <li>Have a physical wheel which I turn one rotation every 300 msec. This is the length in time of a cycle.</li> <li>Read a marker on this wheel using a sensor, such as Sick or Omron. I have this already. Sensor can be PNP or NPN, providing a closed or open connection. I can go via an optocoupler if needed.</li> <li>Once a signal is seen, the arduino should send a (sequential) string using RS232 to a PC. Approximately 90 characters. It is not needed to wait for response.</li> </ul> <p>My question is: would be time for arduino to do this be relatively constant - ie, send out the data at approximately same point in the cycle. Example: signal read at &quot;12&quot; on the clock, data sent around &quot;5&quot;.</p> <p>If possible, what sort of Arduino would I be looking at ?</p> <p>Or do I need something more real-time for such project, like a PLC ?</p>
<blockquote> <p>one rotation every 300 msec.</p> </blockquote> <p>300 ms is a <em>very long time</em> for an Arduino, even for an AVR-based one, like an Uno.</p> <p>I did a little experiment. I generated (with an Arduino...) a periodic signal consisting of a 96 µs-wide negative pulse repeating every 300 ms. I sent that signal to an Arduino Uno running the following code:</p> <pre class="lang-cpp prettyprint-override"><code>const uint8_t sensor_pin = 3; // 90-byte message. const char message[] = &quot;Korem ipsum dolor sit amet, consectetur &quot; &quot;adipiscing elit sed do eiusmod tempor incididunt\r\n&quot;; void setup() { pinMode(sensor_pin, INPUT_PULLUP); Serial.begin(9600); } void loop() { if (digitalRead(sensor_pin) == LOW) { Serial.write(message); // Wait until the signal rises again. while (digitalRead(sensor_pin) == LOW) continue; } } </code></pre> <p>This is not the nicest way to do edge detection, but for this simple test it will do. You may notice that I am not using interrupts for capturing the pulse: 96 µs is long enough to be captured with this simple <code>digitalRead()</code>. I then captured the input and output signals with a dual-channel pocket oscilloscope. Here is a screen capture:</p> <p><a href="https://i.stack.imgur.com/6FXC2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6FXC2.png" alt="Oscilloscope screen capture" /></a></p> <p>The cyan trace at the top is the received pulse. The yellow trace below is the output of the serial port. The negative pulse on this trace that is almost coincident with the received pulse is the start bit. Then the signal rises to transmit the first data bit, which is a 1 (that's why I chose “K” rather than “L” as the first letter).</p> <p>What you can see in this capture is that the latency of the Arduino is tiny at this scale: a small fraction of the duration of the start bit. What you cannot see is the jitter, which is quite large in <em>relative</em> terms, but still small compared to the time scales relevant to you. In short, the delay between the falling edge on the input and the falling edge of the serial port start bit fluctuates roughly between 10 and 20 µs. Yes, those are <strong>micro</strong>seconds. This delay is roughly 20,000 times shorter than the rotation period. If the signal is read at “12” on the clock, the start bit fires at 12 hours with 0 minutes and 2 seconds.</p> <p>Note that, on the other hand, the time needed to send the message at 9600 b/s is 93.6 ms, a significant fraction of the rotation period. And I didn't look at the behavior of the USB-to-serial converter chip, which is another can of worms...</p>
91089
|seeeduino-xiao|
Seeeduino XIAO read PWM duration (period) using timers change Pins freom D2 to D1
2022-10-21T09:56:23.327
<p>I designed a circuitboard and need to proof the function.Therefore i have to modify the code to read from Pins D1 instead of D2. Unfourtunatly i am not that familar with the high level programming so im not sure if i got all changes. Basically all PINS on the circuit are used.</p> <p>Basecode foud here: <a href="https://arduino.stackexchange.com/questions/85741/seeeduino-xiao-write-and-read-pwm-duration-period-using-timers">Seeeduino XIAO write and read PWM duration (period) using timers</a></p> <p>Reading short square waves with Seeeduino XIAO pin D2</p> <pre><code>// Setup TC4 to capture pulse-width and period on digital pin D2 on Seeeduino Xiao volatile boolean periodComplete; volatile uint32_t isrPeriod; volatile uint32_t isrPulsewidth; uint32_t period; uint32_t pulsewidth; void setup() { SerialUSB.begin(115200); // Initialise the native serial port while(!SerialUSB); // Wait for the console to open PM-&gt;APBCMASK.reg |= PM_APBCMASK_EVSYS; // Switch on the event system peripheral GCLK-&gt;GENDIV.reg = GCLK_GENDIV_DIV(1) | // Divide the 48MHz system clock by 1 = 48MHz GCLK_GENDIV_ID(4); // Set division on Generic Clock Generator (GCLK) 4 GCLK-&gt;GENCTRL.reg = GCLK_GENCTRL_IDC | // Set the duty cycle to 50/50 HIGH/LOW GCLK_GENCTRL_GENEN | // Enable GCLK 4 GCLK_GENCTRL_SRC_DFLL48M | // Set the clock source to 48MHz GCLK_GENCTRL_ID(4); // Set clock source on GCLK 4 while (GCLK-&gt;STATUS.bit.SYNCBUSY); // Wait for synchronization GCLK-&gt;CLKCTRL.reg = GCLK_CLKCTRL_CLKEN | // Route GCLK4 to TC4 and TC5 GCLK_CLKCTRL_GEN_GCLK4 | GCLK_CLKCTRL_ID_TC4_TC5; // Enable the port multiplexer on port pin PA10 PORT-&gt;Group[PORTA].PINCFG[10].bit.PMUXEN = 1; // Set-up the pin as an EIC (interrupt) on port pin PA10 PORT-&gt;Group[PORTA].PMUX[10 &gt;&gt; 1].reg |= PORT_PMUX_PMUXE_A; EIC-&gt;EVCTRL.reg |= EIC_EVCTRL_EXTINTEO10; // Enable event output on external interrupt 10 EIC-&gt;CONFIG[1].reg |= EIC_CONFIG_SENSE2_HIGH; // Set event detecting a HIGH level EIC-&gt;INTENCLR.reg = EIC_INTENCLR_EXTINT10; // Disable interrupts on external interrupt 10 EIC-&gt;CTRL.reg |= EIC_CTRL_ENABLE; // Enable EIC peripheral while (EIC-&gt;STATUS.bit.SYNCBUSY); // Wait for synchronization EVSYS-&gt;USER.reg = EVSYS_USER_CHANNEL(1) | // Attach the event user (receiver) to channel 0 (n + 1) EVSYS_USER_USER(EVSYS_ID_USER_TC4_EVU); // Set the event user (receiver) as timer TC4 EVSYS-&gt;CHANNEL.reg = EVSYS_CHANNEL_EDGSEL_NO_EVT_OUTPUT | // No event edge detection EVSYS_CHANNEL_PATH_ASYNCHRONOUS | // Set event path as asynchronous EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_10) | // Set event generator (sender) as external interrupt 10 EVSYS_CHANNEL_CHANNEL(0); // Attach the generator (sender) to channel 0 TC4-&gt;COUNT32.EVCTRL.reg = TC_EVCTRL_TCEI | // Enable the TC event input //TC_EVCTRL_TCINV | // Invert the event input TC_EVCTRL_EVACT_PPW; // Set up the timer for capture: CC0 period, CC1 pulsewidth TC4-&gt;COUNT32.CTRLC.reg = TC_CTRLC_CPTEN1 | // Enable capture on CC1 TC_CTRLC_CPTEN0; // Enable capture on CC0 while (TC4-&gt;COUNT32.STATUS.bit.SYNCBUSY); // Wait for synchronization NVIC_SetPriority(TC4_IRQn, 0); // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest) NVIC_EnableIRQ(TC4_IRQn); // Connect the TC4 timer to the Nested Vector Interrupt Controller (NVIC) TC4-&gt;COUNT32.INTENSET.reg = TC_INTENSET_MC1 | // Enable compare channel 1 (CC1) interrupts TC_INTENSET_MC0; // Enable compare channel 0 (CC0) interrupts TC4-&gt;COUNT32.CTRLA.reg = //TC_CTRLA_PRESCSYNC_PRESC | // Overflow on precaler clock, (rather than the GCLK) TC_CTRLA_PRESCALER_DIV1 | // Set prescaler to 1, 48MHz/1 = 48MHz TC_CTRLA_MODE_COUNT32; // Set TC4/TC5 to 32-bit timer mode TC4-&gt;COUNT32.CTRLA.bit.ENABLE = 1; // Enable TC4 while (TC4-&gt;COUNT32.STATUS.bit.SYNCBUSY); // Wait for synchronization } void loop() { if (periodComplete) // Check if the period is complete { noInterrupts(); // Read the new period and pulse-width period = isrPeriod; pulsewidth = isrPulsewidth; interrupts(); SerialUSB.print(&quot;PW: &quot;); SerialUSB.print(pulsewidth); SerialUSB.print(F(&quot; &quot;)); SerialUSB.print(&quot;P: &quot;); SerialUSB.println(period); periodComplete = false; // Start a new period } } void TC4_Handler() // Interrupt Service Routine (ISR) for timer TC4 { // Check for match counter 0 (MC0) interrupt if (TC4-&gt;COUNT32.INTFLAG.bit.MC0) { TC4-&gt;COUNT32.READREQ.reg = TC_READREQ_RREQ | // Enable a read request TC_READREQ_ADDR(0x18); // Offset address of the CC0 register while (TC4-&gt;COUNT32.STATUS.bit.SYNCBUSY); // Wait for (read) synchronization isrPeriod = TC4-&gt;COUNT32.CC[0].reg; // Copy the period periodComplete = true; // Indicate that the period is complete } // Check for match counter 1 (MC1) interrupt if (TC4-&gt;COUNT32.INTFLAG.bit.MC1) { TC4-&gt;COUNT32.READREQ.reg = TC_READREQ_RREQ | // Enable a read request TC_READREQ_ADDR(0x1A); // Offset address of the CC1 register while (TC4-&gt;COUNT32.STATUS.bit.SYNCBUSY); // Wait for (read) synchronization isrPulsewidth = TC4-&gt;COUNT32.CC[1].reg; // Copy the pulse-width } } </code></pre> <p>Do i only have to change the IOs: from:<br /> PORT-&gt;Group[PORTA].PINCFG[10].bit.PMUXEN = 1;<br /> PORT-&gt;Group[PORTA].PMUX[10 &gt;&gt; 1].reg |= PORT_PMUX_PMUXE_A;<br /> to:<br /> PORT-&gt;Group[PORTA].PINCFG[4].bit.PMUXEN = 1;<br /> PORT-&gt;Group[PORTA].PMUX[4 &gt;&gt; 1].reg |= PORT_PMUX_PMUXE_A;</p> <p>or do i need to mod more code?</p> <p>Thanks for helping.</p>
<p>In addition to the changes you mentioned, your <code>EIC_EVCTRL_EXTINTEO10</code>, <code>EIC_INTENCLR_EXTINT10</code>, and <code>EVSYS_ID_GEN_EIC_EXTINT_10</code> usages will need to be changed to <code>EIC_EVCTRL_EXTINTE4</code>, <code>EIC_INTENCLR_EXTINT4</code> and to <code>EVSYS_ID_GEN_EIC_EXTINT_4</code>, to re-target the event system source, because <code>PORT_PMUX_PMUXE_A</code> on both <a href="https://github.com/Seeed-Studio/ArduinoCore-samd/blob/v1.8.3/variants/XIAO_m0/variant.cpp#L28-L29" rel="nofollow noreferrer">these pins</a> routes the signal to the EIC, but not to the exact same interrupt number. The <code>EIC-&gt;CONFIG</code> line needs to change to the first group of 8 (<code>[0]</code>) and fourth SENSE within that group (<code>EIC_CONFIG_SENSE4_HIGH</code>) to the change to D1 (PA04) uses EXTINT4. This is something I'd left out of the first edit before I'd been able to test. I did eventually find a XIAO to test with and these modifications seem to make it work just fine on digital pin 1 now instead of digital pin 2.</p> <pre class="lang-cpp prettyprint-override"><code>EIC-&gt;EVCTRL.reg |= EIC_EVCTRL_EXTINTE4; EIC-&gt;CONFIG[0].reg |= EIC_CONFIG_SENSE4_HIGH; EIC-&gt;INTENCLR.reg = EIC_INTENCLR_EXTINT4; EIC-&gt;CTRL.reg |= EIC_CTRL_ENABLE; while (EIC-&gt;STATUS.bit.SYNCBUSY); </code></pre> <p>...</p> <pre class="lang-cpp prettyprint-override"><code>EVSYS-&gt;CHANNEL.reg = EVSYS_CHANNEL_EDGSEL_NO_EVT_OUTPUT | EVSYS_CHANNEL_PATH_ASYNCHRONOUS | EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_4) | EVSYS_CHANNEL_CHANNEL(0); </code></pre> <hr /> <p>The changes you'd mentioned and those I've said above as diff:</p> <pre><code>--- original.ino +++ modified.ino @@ -24,14 +24,14 @@ GCLK_CLKCTRL_GEN_GCLK4 | GCLK_CLKCTRL_ID_TC4_TC5; - // Enable the port multiplexer on port pin PA10 - PORT-&gt;Group[PORTA].PINCFG[10].bit.PMUXEN = 1; - // Set-up the pin as an EIC (interrupt) on port pin PA10 - PORT-&gt;Group[PORTA].PMUX[10 &gt;&gt; 1].reg |= PORT_PMUX_PMUXE_A; + // Enable the port multiplexer on port pin PA04 + PORT-&gt;Group[PORTA].PINCFG[4].bit.PMUXEN = 1; + // Set-up the pin as an EIC (interrupt) on port pin PA04 + PORT-&gt;Group[PORTA].PMUX[4 &gt;&gt; 1].reg |= PORT_PMUX_PMUXE_A; - EIC-&gt;EVCTRL.reg |= EIC_EVCTRL_EXTINTEO10; // Enable event output on external interrupt 10 - EIC-&gt;CONFIG[1].reg |= EIC_CONFIG_SENSE2_HIGH; // Set event detecting a HIGH level - EIC-&gt;INTENCLR.reg = EIC_INTENCLR_EXTINT10; // Disable interrupts on external interrupt 10 + EIC-&gt;EVCTRL.reg |= EIC_EVCTRL_EXTINTEO4; // Enable event output on external interrupt 4 + EIC-&gt;CONFIG[0].reg |= EIC_CONFIG_SENSE4_HIGH; // Set event detecting a HIGH level + EIC-&gt;INTENCLR.reg = EIC_INTENCLR_EXTINT4; // Disable interrupts on external interrupt 4 EIC-&gt;CTRL.reg |= EIC_CTRL_ENABLE; // Enable EIC peripheral while (EIC-&gt;STATUS.bit.SYNCBUSY); // Wait for synchronization @@ -40,7 +40,7 @@ EVSYS-&gt;CHANNEL.reg = EVSYS_CHANNEL_EDGSEL_NO_EVT_OUTPUT | // No event edge detection EVSYS_CHANNEL_PATH_ASYNCHRONOUS | // Set event path as asynchronous - EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_10) | // Set event generator (sender) as external interrupt 10 + EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_4) | // Set event generator (sender) as external interrupt 4 EVSYS_CHANNEL_CHANNEL(0); // Attach the generator (sender) to channel 0 TC4-&gt;COUNT32.EVCTRL.reg = TC_EVCTRL_TCEI | // Enable the TC event input </code></pre>
91109
|arduino-ide|
How to turn off the display of line numbers on Mac Arduino IDE?
2022-10-23T01:08:01.997
<p>I'm trying to turn off line numbers on the Mac Arduino IDE but don't see the option for it after navigating to <code>Arduino IDE &gt; Preferences</code>. Below is a screenshot of what I am seeing.</p> <p><a href="https://i.stack.imgur.com/7cIA5.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/7cIA5.jpg" alt="Arduino Preferences" /></a></p> <p>I saw <a href="https://arduino.stackexchange.com/questions/52161/arduino-ide-display-code-line-numbers">this question</a> asked previously, but there is no <code>File &gt; Preferences</code> path on Mac. I am using Version 2.0.0 on macOS (10.14 or newer).</p>
<p>I don't see a proper place to do this in the 2.0.0 IDE preferences. However, modifying the .arduinoIDE/setting.json file to include <code>&quot;editor.lineNumbers&quot;: &quot;off&quot;,</code> seems to work.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;editor.lineNumbers&quot;: &quot;off&quot;, &quot;editor.fontSize&quot;: 14, ... } </code></pre> <p><a href="https://i.stack.imgur.com/qYfDd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qYfDd.png" alt="Shows IDE 2.0.0 with and without line numbers." /></a></p> <p>Edgar Bonet pointed out in a comment that there's still a bunch of empty space in that region. The image above doesn't do a good of showing why though. In the below screenshots I've told the IDE to set a breakout and hovered over where folding region so it displays the fold indicators to make somewhat easier to see that and compare what effect on width results from disabling these things.</p> <p>If you want to save a bit more space you can add turn off the code folding feature, which removes the spaced that would be used for fold indicators with an additional <code>&quot;editor.folding&quot;: &quot;false&quot;,</code> in the settings.json file.</p> <p>For comparison, here's everything enabled, numbers but no folding, folding but no numbers, no folding and no numbers:</p> <p><a href="https://i.stack.imgur.com/Hf7hD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hf7hD.png" alt="Comparison of widths with different combinations of folding and line number settings." /></a></p> <p>I haven't yet found out how to turn off the display of break-point indicators. I assume that it is possible though.</p>
91119
|pins|digispark|
Duinotech ATTINY85 Pinout
2022-10-23T20:26:42.043
<p>I'm sure this is a super nooby question but,</p> <p>what is the pinout of the Digispark ATTINY85 Development Board</p> <p>The board looks like this: <a href="https://i.stack.imgur.com/5vjVs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5vjVs.png" alt="Board" /></a></p> <p>Now the reason why I'm asking this question, when I do <code>digitalWrite(1, HIGH);</code>, the test light will come on. My question is then, what is the virtual number for PB1 (P1 in photo).</p> <p>Also, does that arduino output + or -?</p> <p>Any help is appreciated. Thank You!</p>
<p><a href="https://create.arduino.cc/projecthub/alaspuresujay/use-an-attiny85-with-arduino-ide-07740c" rel="nofollow noreferrer">This</a> seems to show an obvious pinout with an LED connected to p1 (digital pin 1). With &quot;virtual number&quot; I guess you mean the Arduino pin nr. As your code shows you, it's Arduino pin 1.</p>
91122
|interrupt|time|attiny85|
Attiny timer interrupt does not make an interrupt every 1000ms
2022-10-23T23:17:53.527
<p>I'm making a stopwatch using an attiny85, the idea was to use the timer interrupts to count the seconds my theory was: since I set the Attiny85 to run at 1Mhz, I can use a presale of 1024; 1000000 / 1024 = 976.5625 hz, 976.5625hz = 1.024ms, 125ms / 1.024ms = 122.07, so that I need to count to 122 to get a 125ms interrupt, then in the ISR function I can count to 8 to get around 1 second, ( 122 * 1.024 ) * 8 = 999.424ms</p> <p>What is the problem? well, the problem is that I'm not getting something close to 999.424ms, I compere it with my phone's stopwatch and the attiny seems to start well, but then it gets about 2-3 slower than my phone's stopwatch</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;TM1637Display.h&gt; #define CLK 4 #define DIO 3 #define button 1 TM1637Display display (CLK, DIO); int intr_count = 0; byte dots = 0b01000000; volatile int seg; volatile int min; volatile bool start = false; void setup() { display.setBrightness(5); display.clear(); pinMode(button, INPUT); cli(); TCCR0A = 0; TCCR0B = 0; TCCR0B |= B00000101; TIMSK |= B00010000; OCR0A = 122; sei(); } void start_counting(){ if (digitalRead(button) == HIGH){ start = !start; if(start == false){ // display.clear(); seg = 0; min = 0; } while(digitalRead(button) == HIGH); } } void loop() { start_counting(); display.showNumberDecEx(min, dots, true, 2, 0); display.showNumberDec(seg, true, 2, 2); } ISR(TIMER0_COMPA_vect) { TCNT0 = 0; if(start == true){ if (intr_count == 8) { seg++; if(seg == 60){ min++; min = min % 60; } seg = seg % 60; intr_count = 0; } else { intr_count++; } } } </code></pre>
<p>I see three issues with this approach.</p> <p>The first is that you are using a very low quality, uncalibrated time source. The frequency of the internal RC oscillator is good to within a few percent only. It is also very unstable, and hugely dependent on temperature. Using an external 16 Mhz ceramic oscillator should give you a frequency that is no worse than 0.5% off, with a typical error about 0.1%. It is still somewhat unstable though. If you instead are using a <em>crystal</em> oscillator, then you can expect an error about ten times smaller (in the range of 100 ppm), and a very good stability. Depending on you quality requirements, 100 ppm may still not be good enough, in which case you still have the option to measure the drift rate and calibrate it out (see below).</p> <p>The second problem, which has already been raised by 6v6g, is that your timer is counting from zero to 122 inclusive, which gives a period of 123 timer clock cycles. Take a look at the timing diagrams in the datasheet if you need to convince yourself of this. If you want a period of 122, you should set OCR0A to 121.</p> <p>The third problem is that you are resetting the timer with the ISR. This may work in this program, but it is a very fragile approach worth avoiding. The problem is that everything the microcontroller does takes time, and your ISR may even get delayed by another interrupt. If the timer is incremented after rising the interrupt flag but before you reset it, you are missing one count. If you want to have a continuous time scale, <em>never</em> reset your timer. You can either:</p> <ul> <li><p>let it run continuously, undisturbed (and do <code>OCR0A += 122</code> within the ISR),</p> </li> <li><p>or let it reset itself by using the appropriate waveform generation mode (CTC or fast PWM).</p> </li> </ul> <p>Lastly, here is a trick you may use to calibrate your stop watch. Instead of counting the interrupts until the counter reaches 8 (which assumes an interrupt period of exactly 1/8 s), increment a nanosecond counter within the ISR, and count one second once you have one billion nanoseconds:</p> <pre class="lang-cpp prettyprint-override"><code>const uint32_t nanoseconds_per_interrupt = 124928000; ISR(TIMER0_COMPA_vect) { static uint32_t nanoseconds; nanoseconds += nanoseconds_per_interrupt; if (nanoseconds &gt;= 1000000) { nanoseconds -= 1000000; seconds++; // then update minutes, hours... if needed } } </code></pre> <p>This will increment the seconds every eight interrupts... most of the time. From time to time, however, it will take nine interrupts. This adds a little bit of jitter, but prevents the timing errors from accumulating and making the clock drift. If the jitter is visible, you can reduce it by shortening the interrupt period.</p> <p>The value 124928000 I wrote above assumes the ISR is called every 122×1024 cycles of a 1 MHz clock. You can change it to fit a different clock frequency or a different OCR0A setting. The trick is: once you measure the drift rate of your stop watch, you can tweak this number to remove that drift. For example, if you measure the stopwatch and find it is running 0.04% too slow, then you increase that number by 0.04% (that would give 124977971) and the drift is gone.</p> <p><strong>Edit</strong>: In a comment, 6v6gt pointed out a fourth issue in your code, which is likely the biggest issue. Your logic for counting interrupts is:</p> <pre class="lang-cpp prettyprint-override"><code>if (intr_count == 8) { intr_count = 0; } else { intr_count++; } </code></pre> <p>This is counting from 0 to 8 <em>inclusive</em>, and looping with a period of 9 interrupts. A safer idiom for looping with a period of 8 would be:</p> <pre class="lang-cpp prettyprint-override"><code>if (++intr_count &gt;= 8) { intr_count = 0; } </code></pre> <p>Although I would still recommend counting nanoseconds if you want the ability to calibrate your clock.</p>
91131
|sram|assembly|
Does the bootloader use some SRAM?
2022-10-25T10:46:23.877
<p>I want to use all SRAM of an Arduino by writing the code in assembly. But does the bootloader use some SRAM while the program is running, and if the answer is <em>yes</em> would changing that data lead to failure or does the data stored there get corrupted? Thanks for reaching out.</p>
<p>You did not specify what type of Arduino you are using. My answer is for the AVR-based ones.</p> <p>The bootloader does use RAM <em>while it is running</em>. However, once it handles control to your program, the microcontroller is all yours: you are free to use all the RAM.</p> <p>Id did not check with optiboot but, it is possible that the bootloader leaves some stuff in the stack. The C runtime of the avr-libc takes care of this: one of the first things it does is to reset the stack pointer. If you link with the avr-libc, you will find the stack empty. If you don't, I suggest you set the stack pointer to RAMEND at the beginning of your program, just in case.</p>
91134
|arduino-ide|c++|array|callbacks|
Array of Functions
2022-10-26T06:25:50.080
<p>I'm new to C++. How to make a menu without <code>if() {} else {}</code> &amp; <code>switch() case</code>? I made a menu on an array, but for some reason it doesn't compile. How to correct it?</p> <pre><code>typedef void (*cbd)(uint8_t, uint8_t); typedef void (*cbt)(uint8_t, uint8_t); typedef void (*cba)(uint8_t, uint8_t); typedef void (*MenuFunction) (int8_t); class Menu { public: Menu() { updownFns[5] = {updownNone, updownAlarmHours, updownAlarmMinutes, updownTimeHours, updownTimeMinutes}; } static void Setup(cbd display, cbt setTime, cba setAlarm, uint8_t alarmHours, uint8_t alarmMinutes) { cbDisplay = display; cbSetTime = setTime; cbSetAlarms = setAlarm; alarmHours = alarmHours; alarmMinutes = alarmMinutes; cbSetAlarms(alarmHours, alarmMinutes); } // Used for menu.UpDown(dir) callback static void UpDown(int8_t direction) { updownFn(direction); } // Used for menu.Tab() callback static void Tab() { updownFnNum++; updownFn = updownFns[updownFnNum % 5]; } private: static void updownNone(int8_t direction) { } static void updownAlarmHours(int8_t direction) { alarmHours += direction; cbDisplay(alarmHours, alarmMinutes); cbSetAlarms(alarmHours, alarmMinutes); } static void updownAlarmMinutes(int8_t direction) { alarmMinutes += direction; cbDisplay(alarmHours, alarmMinutes); cbSetAlarms(alarmHours, alarmMinutes); } static void updownTimeHours(int8_t direction) { timeHours += direction; cbSetTime(timeHours, timeMinutes); cbDisplay(timeHours, timeMinutes); } static void updownTimeMinutes(int8_t direction) { timeMinutes += direction; cbSetTime(timeHours, timeMinutes); cbDisplay(timeHours, timeMinutes); } static uint8_t alarmHours, alarmMinutes, timeHours, timeMinutes; static uint8_t updownFnNum; // 0-None, 1-AlarmH, 2-AlarmM, 3-TimeH, 4-TimeM static cbd cbDisplay; static cbt cbSetTime; static cba cbSetAlarms; static MenuFunction updownFns[5]; static MenuFunction updownFn; }; uint8_t Menu::alarmHours = 0; uint8_t Menu::alarmMinutes = 0; uint8_t Menu::timeHours = 0; uint8_t Menu::timeMinutes = 0; uint8_t Menu::updownFnNum = 0; cbd Menu::cbDisplay = NULL; cbt Menu::cbSetTime = NULL; cba Menu::cbSetAlarms = NULL; MenuFunction Menu::updownFn = NULL; </code></pre> <p>Output:</p> <pre><code>In file included from app.ino:7:0: menu.h: In constructor 'Menu::Menu()': menu.h:9:109: error: cannot convert '&lt;brace-enclosed initializer list&gt;' to 'MenuFunction {aka void (*)(signed char)}' in assignment updownFns[5] = {updownNone, updownAlarmHours, updownAlarmMinutes, updownTimeHours, updownTimeMinutes}; </code></pre> <p>Thank you!</p>
<p>The C++ language makes a distinction between an <em>initialization</em> and an <em>assignment</em>. An initialization is the initial value you give to a variable at the point where you are defining it. An assignment is the use of the <code>=</code> operator anywhere else. Also, the language does not allow assigning the contents of an array as a whole. You can initialize an array though.</p> <p>This:</p> <pre class="lang-cpp prettyprint-override"><code>Menu() { updownFns[5] = {updownNone, updownAlarmHours, updownAlarmMinutes, updownTimeHours, updownTimeMinutes}; } </code></pre> <p>is an attempt to assign a whole array. It cannot work. If you want to initialize the array, do it at the point where it is being defined, outside of the class definition:</p> <pre class="lang-cpp prettyprint-override"><code>MenuFunction Menu::updownFns[5] = {updownNone, updownAlarmHours, updownAlarmMinutes, updownTimeHours, updownTimeMinutes}; </code></pre>
91145
|arduino-uno|atmega328|array|led-matrix|
Problem with character concatenation algorithm in matrix led
2022-10-26T22:45:00.730
<p>good afternoon, I am making a 7x10 led matrix in which I use a CD4017 to handle the 7 rows and 2 cascaded shift registers to handle the 10 columns. I first tried a programming to turn on my entire led matrix and it worked fine. Then, I tried to make a character appear statically and it worked fine. Next, I tried to make that character sweep from right to left and it worked fine. But, what I am having a hard time with is sweeping the message from right to left smoothly with a column of character to character spacing.</p> <p>What I originally thought is that if I wanted to move a character from right to left, I have to shift the column values for all the rows by an appropriate amount (shift step) and once the character has been shifted enough, I start feeding the column values of the next character in the message for which, the formula that would create the right to left shift effect is: (current_char&lt;scroll) | (next_char&gt;&gt;(8-shift_step)-scroll) But I don't get the expected result, the message scrolls from right to left but it doesn't do it with a column of separation between character and character and it doesn't do it in a fluid way either. In addition to that at the end of sweeping the message appears something strange that should not be there.</p> <p>I recorded a video showing what I am saying: <a href="https://drive.google.com/file/d/1ebO5zassWY060mvWACPhcSLeOi5JmZAC/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1ebO5zassWY060mvWACPhcSLeOi5JmZAC/view</a></p> <p>Code:</p> <pre><code>/* char_data is a two dimensional constant array that holds the 5-bit column values of individual rows for ASCII characters that are to be displayed on a 7x10 matrix. */ const byte char_data[95][7]={ {0, 0, 0, 0, 0, 0, 0}, // space {0b100, 0b100, 0b100, 0b100, 0b100, 0, 0b100}, // ! {0b1010, 0b1010, 0b1010, 0, 0, 0, 0}, // &quot; {0b1010, 0b1010, 0b11111, 0b1010, 0b11111, 0b1010, 0b1010}, // # {0b100, 0b1111, 0b10100, 0b1110, 0b101, 0b11110, 0b100}, // $ {0b11000, 0b11001, 0b10, 0b100, 0b1000, 0b10011, 0b11}, // % {0b1000, 0b10100, 0b10100, 0b1000, 0b10101, 0b10010, 0b1101}, // &amp; {0b100, 0b100, 0b100, 0, 0, 0, 0}, // ' {0b100, 0b1000, 0b10000, 0b10000, 0b10000, 0b1000, 0b100}, // ( {0b100, 0b10, 0b1, 0b1, 0b1, 0b10, 0b100}, // ) {0b100, 0b10101, 0b1110, 0b100, 0b1110, 0b10101, 0b100}, // * {0, 0b100, 0b100, 0b11111, 0b100, 0b100, 0}, // + {0, 0, 0, 0, 0b100, 0b100, 0b1000}, // , {0, 0, 0, 0b11111, 0, 0, 0}, // - {0, 0, 0, 0, 0, 0, 0b100}, // . {0, 0b1, 0b10, 0b100, 0b1000, 0b10000, 0}, // / {0b1110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b1110}, // 0 {0b110, 0b1100, 0b100, 0b100, 0b100, 0b100, 0b1110}, // 1 {0b1110, 0b10001, 0b1, 0b110, 0b1000, 0b10000, 0b11111}, // 2 {0b11111, 0b1, 0b10, 0b110, 0b1, 0b10001, 0b1111}, // 3 {0b10, 0b110, 0b1010, 0b10010, 0b11111, 0b10, 0b10}, // 4 {0b11111, 0b10000, 0b11110, 0b1, 0b1, 0b10001, 0b1110}, // 5 {0b01110, 0b10001, 0b10000, 0b11110, 0b10001, 0b10001, 0b1110}, // 6 {0b11111, 0b1, 0b10, 0b100, 0b1000, 0b1000, 0b1000}, // 7 {0b01110, 0b10001, 0b10001, 0b1110, 0b10001, 0b10001, 0b1110}, // 8 {0b01110, 0b10001, 0b10001, 0b1111, 0b1, 0b10001, 0b1110}, // 9 {0, 0, 0b100, 0, 0b100, 0, 0}, // : {0, 0, 0b100, 0, 0b100, 0b100, 0b1000}, // ; {0b10, 0b100, 0b1000, 0b10000, 0b1000, 0b100, 0b10}, // &lt; {0, 0, 0b11111, 0, 0b11111, 0, 0}, // = {0b1000, 0b100, 0b10, 0b1, 0b10, 0b100, 0b1000}, // &gt; {0b1110, 0b10001, 0b1, 0b10, 0b100, 0, 0b100}, // ? {0b1110, 0b10001, 0b10111, 0b10101, 0b10110, 0b10000, 0b1111}, // @ {0b1110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001}, // A {0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110}, // B {0b1110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b1110}, // C {0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110}, // D {0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111}, // E {0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000}, // F {0b1110, 0b10001, 0b10000, 0b10111, 0b10101, 0b10001, 0b1110}, // G {0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001}, // H {0b11111, 0b100, 0b100, 0b100, 0b100, 0b100, 0b11111}, // I {0b1, 0b1, 0b1, 0b1, 0b1, 0b10001, 0b1110}, // J {0b10001, 0b10001, 0b10010, 0b11100, 0b10010, 0b10001, 0b10001}, // K {0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111}, // L {0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001}, // M {0b10001, 0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001}, // N {0b1110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b1110}, // O {0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000}, // P {0b1110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10011, 0b1111}, // Q {0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b10001}, // R {0b1111, 0b10000, 0b10000, 0b1110, 0b1, 0b1, 0b11110}, // S {0b11111, 0b100, 0b100, 0b100, 0b100, 0b100, 0b100}, // T {0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b1110}, // U {0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b1010, 0b100}, // V {0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001}, // W {0b10001, 0b10001, 0b1010, 0b100, 0b1010, 0b10001, 0b10001}, // X {0b10001, 0b10001, 0b1010, 0b100, 0b100, 0b100, 0b100}, // Y {0b11111, 0b1, 0b10, 0b100, 0b1000, 0b10000, 0b11111}, // Z {0b1110, 0b1000, 0b1000, 0b1000, 0b1000, 0b1000, 0b1110}, // [ {0, 0b10000, 0b1000, 0b100, 0b10, 0b1, 0}, // backward slash {0b1110, 0b10, 0b10, 0b10, 0b10, 0b10, 0b1110}, // ] {0, 0, 0b100, 0b1010, 0b10001, 0, 0}, // ^ {0, 0, 0, 0, 0, 0, 0b11111}, // _ {0b1000, 0b100, 0b10, 0, 0, 0, 0}, // ` {0, 0, 0b1110, 0b1, 0b1111, 0b10001, 0b1111}, // a {0b10000, 0b10000, 0b10000, 0b11110, 0b10001, 0b10001, 0b11110}, // b {0, 0, 0b1110, 0b10001, 0b10000, 0b10001, 0b1110}, // c {0b1, 0b1, 0b1, 0b1111, 0b10001, 0b10001, 0b1111}, // d {0, 0, 0b1110, 0b10001, 0b11111, 0b10000, 0b1111}, // e {0b1110, 0b1001, 0b11100, 0b1000, 0b1000, 0b1000, 0b1000}, // f {0, 0, 0b1110, 0b10001, 0b1111, 0b1, 0b1110}, // g {0b10000, 0b10000, 0b10000, 0b11110, 0b10001, 0b10001, 0b10001}, // h {0b100, 0, 0b100, 0b100, 0b100, 0b100, 0b1110}, // i {0b1, 0, 0b11, 0b1, 0b1, 0b10001, 0b1110}, // j {0b10000, 0b10000, 0b10001, 0b10010, 0b11100, 0b10010, 0b10001}, // k {0b1100, 0b100, 0b100, 0b100, 0b100, 0b100, 0b1110}, // l {0, 0, 0b11110, 0b10101, 0b10101, 0b10101, 0b10101}, // m {0, 0, 0b11110, 0b10001, 0b10001, 0b10001, 0b10001}, // n {0, 0, 0b1110, 0b10001, 0b10001, 0b10001, 0b1110}, // o {0, 0, 0b1111, 0b1001, 0b1110, 0b1000, 0b1000}, // p {0, 0, 0b1111, 0b10001, 0b1111, 0b1, 0b1}, // q {0, 0, 0b10111, 0b11000, 0b10000, 0b10000, 0b10000}, // r {0, 0, 0b1111, 0b10000, 0b1110, 0b1, 0b11110}, // s {0b100, 0b100, 0b1110, 0b100, 0b100, 0b100, 0b11}, // t {0, 0, 0b10001, 0b10001, 0b10001, 0b10011, 0b1101}, // u {0, 0, 0b10001, 0b10001, 0b10001, 0b1010, 0b100}, // v {0, 0, 0b10001, 0b10001, 0b10101, 0b11111, 0b10101}, // w {0, 0, 0b10001, 0b1010, 0b100, 0b1010, 0b10001}, // x {0, 0, 0b10001, 0b10001, 0b1111, 0b1, 0b11110}, // y {0, 0, 0b11111, 0b10, 0b100, 0b1000, 0b11111}, // z {0b10, 0b100, 0b100, 0b1000, 0b100, 0b100, 0b10}, // { {0b100, 0b100, 0b100, 0b100, 0b100, 0b100, 0b100}, // | {0b1000, 0b100, 0b100, 0b10, 0b100, 0b100, 0b1000}, // } {0, 0, 0, 0b1010, 0b10101, 0, 0} // ~ }; char message[] = &quot;MATRIX LED 7X10 WITH ATMEGA328p&quot;; int string_length = strlen(message); byte shift_step = 1; void setup(){ // PORTB as output. // Pin 13: ClockRegister // Pin 12: Latch // Pin 11: Data // Pin 10: Reset // Pin 9: Clock4017 DDRB = 0b111111; // Makes sure the 4017 value is 0. PORTB |= (1 &lt;&lt; PB2); PORTB &amp;= ~(1 &lt;&lt; PB2); Serial.begin(9600); } void send_data(uint16_t data){ uint16_t mask = 1, flag = 0; for (byte i=0; i&lt;10; i++){ flag = data &amp; mask; if (flag) PORTB |= (1 &lt;&lt; PB3); else PORTB &amp;= ~(1 &lt;&lt; PB3); PORTB |= (1 &lt;&lt; PB5); PORTB &amp;= ~(1 &lt;&lt; PB5); mask &lt;&lt;= 1; } PORTB |= (1 &lt;&lt; PB4); PORTB &amp;= ~(1 &lt;&lt; PB4); } void display_pattern(byte loops){ for (byte c=0; c&lt;string_length; c++){ // For each character for (byte scroll=0; scroll&lt;10; scroll++){ // For each column. for (byte t=0; t&lt;loops; t++){ // The delay we get with loops. for (byte z=0; z&lt;7; z++){ // For each row. // To obtain the position of the current character in the char_data array, subtract 32 from the ASCII value of the character itself. byte index = message[c]; byte temp = char_data[index-32][z]; byte index_2 = message[c+1]; byte temp_2 = char_data[index_2-32][z]; send_data((temp&lt;&lt;scroll) | (temp_2&gt;&gt;(8-shift_step)-scroll)); delayMicroseconds(800); // Clear the row so we can go on to the next row without smearing. send_data(0); // On to the next row. PORTB |= (1 &lt;&lt; PB1); PORTB &amp;= ~(1 &lt;&lt; PB1); } // Select the first row. PORTB |= (1 &lt;&lt; PB2); PORTB &amp;= ~(1 &lt;&lt; PB2); } } } } void loop(){ display_pattern(10); delay(100000); } </code></pre> <p>I appreciate the help.</p>
<p>Here are a few issues that I noticed in this code. I think that, if you manage to address them, you should get a smooth display:</p> <ol> <li><p>In the expression <code>(temp_2&gt;&gt;(8-shift_step)-scroll)</code>, the amount of shift will be negative when <code>scroll</code> gets larger than 7. A righ shift by a negative amount is not a left shift: it is undefined behavior. Judging by the video, it seems the compiler does no shit at all in this case.</p> </li> <li><p>If you want a one pixel space between the characters, you should move to the next character in the string every six pixels, thus the scroll variable should count from 0 to 5.</p> </li> <li><p>Be aware that there could be up to three characters simultaneously (partially) displayed on the screen: when one character is centered, you should be able to see the edges of both its neighbors.</p> </li> <li><p>As noted by hcheung in a comment, when you get to the last character in the string, the expression <code>message[c+1]</code> is reading past the end of that string.</p> </li> </ol>
91147
|arduino-uno|arduino-ide|
Connect OLED SSD1306 to Elegoo Uno R3
2022-10-27T09:54:53.580
<p>I'm trying to connect the <a href="https://i.stack.imgur.com/yBtYQ.jpg" rel="nofollow noreferrer">OLED SSD1306</a> screen to my Elegoo Uno R3 and display something using Arduino IDE. However, nothing shows up on the screen for some reason.</p> <p>I have connected every pin in the following way:</p> <ul> <li>VCC: 3.3V</li> <li>GND: GND</li> <li>SCL: A5</li> <li>SDA: A4</li> </ul> <p>You can see the setup in the following pictures:</p> <p><a href="https://i.stack.imgur.com/yBtYQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yBtYQ.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/3IA3T.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3IA3T.jpg" alt="enter image description here" /></a></p> <p>Then, I'm using the code from <a href="https://randomnerdtutorials.com/guide-for-oled-display-with-arduino/" rel="nofollow noreferrer">this tutorial</a>, that is, <a href="https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/OLED/oled_adafruit_demo.ino" rel="nofollow noreferrer">this code</a>, to see if the setup is correct, but nothing shows up on the screen. My question is: does anybody know if this is right way to do it? Even though I'm using analog pins and the screen needs digital ones, <a href="https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/" rel="nofollow noreferrer">I read online</a> that it doesn't matter:</p> <blockquote> <p>The analog input pins can be used as digital pins, referred to as A0, A1, etc. The exception is the Arduino Nano, Pro Mini, and Mini’s A6 and A7 pins, which can only be used as analog inputs.</p> </blockquote> <p>I also saw in <a href="https://epow0.org/%7Eamki/car_kit/Datasheet/ELEGOO%20UNO%20R3%20Board.pdf" rel="nofollow noreferrer">Elegoo Uno R3's guide</a> that the A4 and A5 pins are used for the I2C protocol, which is the one that this OLED screen uses:</p> <p><a href="https://i.stack.imgur.com/GHsTU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GHsTU.jpg" alt="enter image description here" /></a></p> <p>So as far as I know, from the hardware point of view, everything seems to be correct, right?</p>
<p>You are close. Looks like you have a run-of-the-mill, clone [not Adafruit], 128x64 LCD with / I2C interface.</p> <ol> <li>Determine the I2C address by flipping it over and seeing which side a 0 ohm resistor or solder blob is on - either 0 or 1. If it is on the '0' side, the address is 0x3C if it is on the '1' side, it is 0x3D.</li> </ol> <p>Here is a photo of the back and with the address of 0x3c.</p> <p><a href="https://i.stack.imgur.com/j3syz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j3syz.jpg" alt="enter image description here" /></a></p> <p>If the back of yours looks very different, locate and run an I2C device scanner to find the address of your display.</p> <ol start="2"> <li>Do not use the code that you linked.</li> </ol> <p>From the Arduino IDE, install or update the the Adafruit SSD1306 library, Version 2.57 is what I used to test this.</p> <p>Once the library is in place, load the example SSD1306_128X64_I2C</p> <p>Locate this line (near the beginning of the code):</p> <p>#define SCREEN_ADDRESS 0x3D ///&lt; See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32</p> <p>Change 0x3D to 0x3C if you need to (as determined earlier). I don't think it is an Adafruit screen, so you can ignore the comment.</p> <ol start="3"> <li>Triple check your 4 connections</li> </ol> <p>Run demo and audibly gasp - &quot;cool&quot;.</p> <p>PS: Mine works on either 3.3V or 5V</p>
91149
|servo|
How to determine the minimum time for a servo to reach its destination?
2022-10-27T13:32:33.850
<p>We all know servos don't move instantly, which is why it is common to put a delay or a millis() loop whenever you issue a servo.write() command to give it time to reach its target before moving on to the next thing.</p> <p>What irks me though is that this could be inefficient in situations where the last servo position might be close to its target - you might only need a very short delay in those cases, whereas if it has to sweep the full 359 degrees, you might want more time.</p> <p>I was disappointed that servo.read() is completely useless for this task (why even include it in the library?) as the following code illustrates:</p> <pre><code>#include &lt;Adafruit_TiCoServo.h&gt; Adafruit_TiCoServo servo; const uint8_t PIN_SERVO = 9; void setup() { servo.attach(PIN_SERVO); Serial.begin(9600); Serial.println(&quot;start&quot;); servo.write(180); delay(1000); int pos; while(pos != 0){ pos = servo.read(); Serial.println(pos); // because it only returns what the last write() operation // was sent, it immediately thinks it's at pos 0 and exits. servo.write(0); } Serial.println(&quot;Done&quot;); } </code></pre> <p>So that sucks. It seems that my options are:</p> <ol> <li>just use a long delay that accommodates the worst-case scenario. I hate this.</li> <li>add a limit switch at the final target position and just read the state of that switch</li> <li>build some kind of elaborate encoder that you can read an absolute angle from or buy a more expensive servo that can tell you this info</li> </ol> <p>For reference the servo I'm playing with is a hobby servo: MG90S</p> <p>Specifically my question is to confirm that there are no other options available for the MG90S other than what I've listed above.</p>
<p>in this case there is mostly one simple solution, and there are some better ones.</p> <p><strong>the problem you faced with the method:</strong> First of all, the read() function indeed only returns what you send to it, it mostly is useful for if you want to know what position you send it to in some other part of code(for example can be used to plan what way to go first if you need to go to many points, or if you already are going to the desired position). but since the rc servo has only one signal wire and that wire sends no signals back you don't know what state they are in, rc servo's are mostly for ease of use and not for accuracy and speed, if you need that you can look into a real servo(stepper motor). so yes that function doesn't return the actual position, it returns the desired position.</p> <p><strong>Solution1:</strong> the easy software based method: to do this you can either read the datasheet to read the speed in duration per degree or measure it, and then use that to calculate the time it would take. <em>actually here the Servo.read() function really comes in use, so this is a perfect example of why you would actually sometimes need or want it.</em></p> <ol> <li>save the duration in miliseconds per degree in a variable.</li> <li>next just before you write to the servo use Servo.read() to get the current theoretical position and use that combined with the position you want to go to calculate the difference in dergees (for example 100 and 40 results in a difference of 60), then multiply that with the duration per step. and you will have the answer of how long a change would take.</li> </ol> <p><strong>Example1</strong> <em>warning, untested, might contain spelling mistakes and such</em></p> <pre><code> /* tuned delay Sweep This example code is in the public domain. No warranty modified 27 March 2023 by Daan V.Loon */ #include &lt;Servo.h&gt; #define DELAYPERDEGREE 2 //this is the value for the sg90 servo from the datasheet(0,12s(120ms)per 60degrees. #define SAFETYMARGIN 110 //this is to add 10% extra time to wait, to make sure it finishes in time even under load. //# define is used kind of like a variable that doesn't need to change, purely in code and not in ram unsigned long waitDuration=0;//variable that shows how long to wait. Servo myservo; unsigned long CalcWait(Servo s,int desiredPosition)//method to calculate and return duration to wait in ms 1000ms is 1 s. { int spos=s.read(); if(spos&gt;desiredPosition){return (((spos-desiredPosition)*DELAYPERDEGREE)*SAFETYMARGIN)/100;} else{ return(((desiredPosition-spos)*DELAYPERDEGREE)*SAFETYMARGIN)/100;} }//end of method void ServoAndWait(int pos){ //insert range limiting code here if needed, warning this method doesn't check if you try to use numbers bigger or smaller than your servo or the servo library can actually handle. waitDuration=CalcWait(myservo,pos);//call method to update how long to wait, needs to be done before telling the servo to move. myservo.write(pos);//tell servo to rotate delay(waitDuration);//blocking wait for servo to complete } void setup() { myservo.attach(2); ServoAndWait(180);//rotate to 180 degrees and wait until it should be there+10% with the safetymargin of 110 } void loop() { ServoAndWait(0); ServoAndWait(180); //this should reult in the famous sweep example, however then at the max speed of your servo, this way you can test it. //to optimize speed use a safetymargin far over 100(like 200 or such) then reduce it until you see it just stop or just not stop anymore at the edges. //also make sure to first test if your servo can actually handle 0 and 180 degrees, for example first test if it moves if you tell it to go from 10 to 0 and from 170 to 180, not all servos reach the full 180 degree range. } </code></pre> <p><strong>Example2:(no comments)</strong></p> <pre><code>/* tuned delay Sweep This example code is in the public domain. No Warranty modified 27 March 2023 by Daan V.Loon */ #include &lt;Servo.h&gt; #define DELAYPERDEGREE 2 #define SAFETYMARGIN 110 unsigned long waitDuration = 0; Servo myservo; unsigned long CalcWait(Servo s, int desiredPosition) { int spos = s.read(); if (spos &gt; desiredPosition) { return (((spos - desiredPosition) * DELAYPERDEGREE) * SAFETYMARGIN) / 100; } else { return (((desiredPosition - spos) * DELAYPERDEGREE) * SAFETYMARGIN) / 100; } } void ServoAndWait(int pos) { waitDuration = CalcWait(myservo, pos); myservo.write(pos); delay(waitDuration); } void setup() { myservo.attach(2); ServoAndWait(180); } void loop() { ServoAndWait(0); ServoAndWait(180); } </code></pre> <p><strong>Example3:</strong> <em>Shorter and more stack overflow alien themed for people who just copy paste or find this clearer</em></p> <pre><code>/* tuned delay Sweep This example code is in the public domain. No Warranty modified 27 March 2023 by Daan V.Loon */ #include &lt;Servo.h&gt; #define DELAYPERDEGREE 2 #define SAFETYMARGIN 110 Servo myservo; unsigned long CalcWait(Servo s, int desiredPosition) { int spos = s.read(); return (spos&gt;desiredPosition?((spos - desiredPosition) * DELAYPERDEGREE * SAFETYMARGIN) / 100 : ((desiredPosition - spos) * DELAYPERDEGREE * SAFETYMARGIN) / 100); } unsigned long waitDuration = 0; void ServoAndWait(int pos) { waitDuration = CalcWait(myservo, pos); myservo.write(pos); delay(waitDuration); } ////---code you would see below, headers and functions and variables above---//// void setup() { myservo.attach(2); } void loop() { ServoAndWait(0); ServoAndWait(180); } </code></pre> <p>These above should be fully functional codes that should work for you, they all work the same. I didn't test it with a servo however, but the logic worked when I tested that. also make sure to change the delay per degree to whatever your datasheet says, in this case the datasheet said 0.12s/60 degrees sg90(very common servo for arduino) so I turned seconds into miliseconds and divided it by 60, so 120/60=2, if you have a much faster servo or need more accurate results for different servos you can use the safety margin to tune, or you can use microseconds in the calculations or such, or just multiply the numbers by 10 and then at the end of the calculations divide it by 10 before returning.</p> <p><strong>Then here is also the more difficult hardware version</strong> to do this you can either try to use the servo's buildin hardware and modify the servo with a 4th wire, either add it to the rotation sensor/potentiometer, or add it to the chip if it has a place where you can read it directly, with this you are on your own however since it is very speciffic for every servo.</p> <p>a more easy way to do this is to use a compactor(or something else that gives you one digital output(typical rc servos will always keep the motor on,and just very rapidly change direction once they are on position, if it actually stops you might just want to read it like a normal digital signal(perhaps do something to protect against motor spikes), and read the wires both standalone instead of comparing them to each other) to compare the voltages on the wires to the motor in the servo, since when it moves one side has a higher voltage than the other side, when it stops, they either are equal or rapidly change to keep position. so you just check for whenever it changes. or if you know the direction you can be even more accurate and fast. this ofcource requires you opening up the servo.</p> <p>or you can indeed add something like a rotary encoder, no need for a complex one, since you can just count the stripes and if you suddenly don't get changes anymore the servo is also stopped in case you missed some, or you can use something like a small microphone or vibration meter since the servo when it moves, this however may become inaccurate under higher load. just try to avoid reading it with analog signals, since for what you want to use it for analog signals can be really slow.</p> <p><strong>also</strong> you might want to look into non blocking delays, it won't make the servo's faster, but it allows you to do other things while the servo is moving so you won't have to wait until it is finished.</p>
91154
|array|variables|memory-usage|memory|
Conditional assignment of array
2022-10-27T22:37:01.507
<p>I have some really long global variable arrays filled with data.</p> <p>There is a single function that processes the data. The function works on only one array everytime. This arrays value changes every iteration and gets the value from the global variable arrays.</p> <p>Since i declare lots of global variable arrays, in order to pass them to the array_to_be_processed_by_the function, the memory is filled up really quickly.</p> <p>What is the best way to conditionally give values to the array?</p> <p>For example, there could be a counter in the program, and if the counter is a particular value, the array would be initialized with certain data. Of course, i would also have to call the function, and i would have to keep track of the counter and increase it and zero it at the beginning of the loop, to start from the beginning.</p> <p>In this approach, only one variable would always be initialized.</p> <pre><code>PSEUDOCODE: int looper = 0; void loop() { switch(looper) { case 0: my_array[] = {DATA HERE}; exec_func(myarray); looper++; continue; case 1: ...... case 'last_case': ... looper = 0; break; } } </code></pre> <p>However, i am not sure if this approach is the correct one. Especially for a microcontroller.</p> <p>One obvious issue, is that the array values are not necessarily the same size. Therefore, the base array should be destroyed at each <code>case</code>? If this is good approach, should <code>new/delete</code> be used on an arduino?</p> <p>What is the best approach to conditionally initialize an array, so that i don't get out of memory</p>
<p>Let's consider this:</p> <pre class="lang-cpp prettyprint-override"><code>case 0: my_array[] = {DATA HERE}; exec_func(myarray); </code></pre> <p>This is not quite valid C++, but let's pretend you get the syntax right to make it work. The problem is: doing this will not help you save memory. Where do you think the compiler is going to store <code>{DATA HERE}</code>? In memory, right. It will be stored as an <em>anonymous</em> array. Then the initialization of <code>my_array</code> will make a <em>second copy</em> of the data in memory, this time in a named array.</p> <p>You can avoid this second copy by naming your arrays of constants, and passing the correct one to your function:</p> <pre class="lang-cpp prettyprint-override"><code>// At global scope: const int my_array_0[] = {...}; const int my_array_1[] = {...}; // Within the switch/case: case 0: exec_func(my_array_0); </code></pre> <p>You can even avoid the <code>switch</code>/<code>case</code> altogether by using an array of pointers, but that is irrelevant to your current problem.</p> <p>Your idea of initializing only the array you actually need can work if you manage to do it <em>procedurally</em>, i.e. implementing some recipe with instructions, rather than copying a set of constant:</p> <pre class="lang-cpp prettyprint-override"><code>case 0: { int my_array[array_size]; for (int i = 0; i &lt; array_size; i++) { my_array[i] = some_expression_to_compute_this_array_item; } exec_func(myarray); } </code></pre> <p>This is not always feasible though.</p> <p>If you really have to store the constants in the program, and you are using an AVR-based Arduino (like the Uno, Mega, Micro...), then you can save RAM by storing the arrays of constants in flash memory, and copying only the one you need to RAM:</p> <pre class="lang-cpp prettyprint-override"><code>// At global scope: const int my_array_0[] PROGMEM = {...}; const int array_size_0 = sizeof my_array_0 / sizeof my_array_0[0]; const int my_array_1[] PROGMEM = {...}; const int array_size_1 = sizeof my_array_1 / sizeof my_array_1[0]; // Within the switch/case: case 0: { int my_array[array_size_0]; // array in RAM memcpy_P(my_array, my_array_0, sizeof my_array); exec_func(my_array); } case 1: { int my_array[array_size_1]; // array in RAM memcpy_P(my_array, my_array_1, sizeof my_array); exec_func(my_array); } </code></pre> <p>Check the documentations of <a href="https://www.arduino.cc/reference/en/language/variables/utilities/progmem/" rel="nofollow noreferrer">PROGMEM</a> and <a href="https://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html#gad92fa2ebe26e65fa424051047d21a0eb" rel="nofollow noreferrer"><code>memcpy_P()</code></a> for the details.</p> <p>If you go this route, you may consider modifying the function <code>exec_func()</code> so that it expects its parameter to be a pointer to flash instead of a pointer to RAM. Then you will completely avoid the copy in RAM.</p> <hr /> <p><strong>Edit:</strong> expanding on the idea of passing a pointer to flash.</p> <p>The C++ compiler doesn't really know the difference between a pointer to RAM and a pointer to flash. If you want to pass a pointer to flash to a function, you have to write the function in such a way that it expects a pointer to flash. For example, this function prints out the contents of a flash-based array:</p> <pre class="lang-cpp prettyprint-override"><code>// The argument should be a pointer to flash. void exec_func(const int *data) { for (int i = 0; i &lt; array_size; i++) { int number = pgm_read_word(&amp;data[i]); Serial.println(number); } } </code></pre> <p>Note that the array is not accessed directly (evaluating <code>data[i]</code> would give garbage). Instead, the address of the element you want (<code>&amp;data[i]</code>, a flash address) is passed to the macro <code>pgm_read_word()</code>, which uses inline assembly to get the relevant data from the flash.</p> <p>Now you can call this function passing it the address of a <code>PROGMEM</code> array, as in <code>exec_func(my_array_0);</code>.</p> <p>Just for completeness, I will show you how to use an array of pointers to avoid the <code>switch</code>/<code>case</code> construct:</p> <pre class="lang-cpp prettyprint-override"><code>const int my_array_0[] PROGMEM = {...}; const int my_array_1[] PROGMEM = {...}; ... const int *arrays[] = {my_array_0, my_array_1, ...}; int looper = 0; void loop() { exec_func(arrays[looper]); if (++looper == number_of_arrays) looper = 0; } </code></pre> <p>Note that here <code>arrays</code> is a RAM-based array. That's why you can access the elements directly as <code>arrays[looper]</code>. These elements, however, are pointers to flash-based arrays. If you have so many arrays that <code>arrays</code> gets too big, you might consider putting it also in flash.</p>
91155
|arduino-uno|pwm|frequency|
Changing Frequency of PWM Pin on Arduino Uno
2022-10-27T22:39:06.583
<p>I am trying to change the frequency of the PWM output from an Arduino Uno R3 (Been using Pin 9) to 200 Hz with a duty cycle of 20%. This is for an ESC that is connected to a 12V motor, and I know the ESC works as if I input a 200 HZ wave from a waveform generator the motor runs. However, I have been finding it difficult to do the same thing with an Arduino Uno and I believe it is due to the frequency being a default of 490 Hz, so I need a way to change that frequency to 200 Hz. Are there any libraries or specific ways to do so?</p> <p>Thanks!</p>
<p>You can also use my newly-created <a href="https://github.com/khoih-prog/AVR_PWM" rel="nofollow noreferrer"><strong>AVR_PWM</strong></a> library to shield you from dealing with complex hardware registers</p> <p>For example</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;AVR_PWM.h&quot; #if ( PWM_USING_ATMEGA2560 ) // Pins tested OK in Mega //#define pinToUse 12 // Timer1B on Mega //#define pinToUse 11 // Timer1A on Mega //#define pinToUse 9 // Timer2B on Mega //#define pinToUse 2 // Timer3B on Mega //#define pinToUse 3 // Timer3C on Mega //#define pinToUse 5 // Timer3A on Mega //#define pinToUse 6 // Timer4A on Mega //#define pinToUse 7 // Timer4B on Mega #define pinToUse 8 // Timer4C on Mega //#define pinToUse 46 // Timer5A on Mega //#define pinToUse 45 // Timer5B on Mega //#define pinToUse 44 // Timer5C on Mega #elif ( PWM_USING_ATMEGA_32U4 ) // Pins tested OK on 32u4 //#define pinToUse 5 // Timer3A on 32u4 #define pinToUse 9 // Timer1A on 32u4 //#define pinToUse 10 // Timer1B on 32u4 #else // Pins tested OK on Nano / UNO #define pinToUse 9 // Timer1A on UNO, Nano, etc //#define pinToUse 10 // Timer1B on UNO, Nano, etc //#define pinToUse 5 // Timer0B on UNO, Nano, e //#define pinToUse 3 // Timer2B on UNO, Nano, etc #endif //creates pwm instance AVR_PWM* PWM_Instance; float frequency; float dutyCycle; void setup() { Serial.print(F(&quot;\nStarting PWM_Basic on &quot;)); Serial.println(BOARD_NAME); Serial.println(AVR_PWM_VERSION); //assigns PWM frequency of 200 Hz and a duty cycle of 0% PWM_Instance = new AVR_PWM(pinToUse, 200, 0); } void loop() { frequency = 200; dutyCycle = 20; PWM_Instance-&gt;setPWM(pinToUse, frequency, dutyCycle); delay(10000); dutyCycle = 90; PWM_Instance-&gt;setPWM(pinToUse, frequency, dutyCycle); delay(10000); } </code></pre>
91156
|arduino-uno|breadboard|
Arduino not recognizing external microcontroller
2022-10-28T01:40:54.963
<p>I've been trying to follow the official <a href="https://docs.arduino.cc/built-in-examples/arduino-isp/ArduinoToBreadboard" rel="nofollow noreferrer">Arduino instructions</a> on how to program and power an external breadboard, and I've gotten a pack of ATmega328p's that may or may not have been preloaded with the bootloader (found <a href="https://www.digikey.com/en/products/detail/universal-solder-electronics-ltd/ATMEGA328P-PU-Arduino-Bootloader/16822123" rel="nofollow noreferrer">here</a>). From the title, I assumed that they were, in fact, preloaded, but I followed the instructions to &quot;reload it&quot; from a working Arduino (with its original microcontroller), and I did it with the following circuit setup (this is the best image that I have of it, unfortunately, I promise I've checked that the wiring actually is equivalent to the original diagram, just shifted around for convenience on the breadboard):</p> <p><a href="https://i.stack.imgur.com/M0l4b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M0l4b.png" alt="enter image description here" /></a></p> <p>I'm not sure whether I should've kept the original microcontroller in, as the guide ambiguously shows a void in the area where the controller should be in the provided diagram...</p> <p><a href="https://i.stack.imgur.com/qPZNg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qPZNg.png" alt="enter image description here" /></a></p> <p>...but my thinking was that the Arduino basically isn't anything without its attached microcontroller, so attempting to &quot;send&quot; bootloader code to a separate microcontroller would require a plugged in microcontroller, and that was the only way I got it to work.</p> <p>With all this set up, I tried to test using this new microcontroller, and it worked perfectly when mounted in the provided microcontroller area. However, when I tried to follow this up with the steps detailed in the guide, <a href="https://docs.arduino.cc/built-in-examples/arduino-isp/ArduinoToBreadboard#uploading-using-an-arduino-board" rel="nofollow noreferrer">found here</a>, with the following circuit (slightly better angle):</p> <p><a href="https://i.stack.imgur.com/WtIeI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WtIeI.png" alt="enter image description here" /></a></p> <p>...I was faced with errors of being unable to connect.</p> <p><a href="https://i.stack.imgur.com/AAoxd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AAoxd.png" alt="enter image description here" /></a></p> <p>From what I understand, it seems like the Arduino should automatically detect that no microcontroller is plugged in, hence allowing the stated &quot;FTDI chip can talk to the microcontroller on the breadboard instead&quot; from the guide. However, the error I'm getting seems to be the same as the error I got when I just plainly tried to send code or program without any microcontroller connected, so I'm assuming this implies that it can't find any microcontroller, either internal or standalone.</p> <p>From googling this error, it seems that others have had this problem with seemingly no solution, and I have absolutely no idea how I could fix this. If there's something I'm missing, would greatly appreciate the help.</p> <p>side note, when I was idly testing out the program with a tiny test circuit that lights up an LED, after programming it with a program that turns on a GPIO pin, connecting that pin to the LED, it did in fact light up. I'm concluding this means that the setup of the actual microcontroller is functional, but it's unable to be written to. this has also happened with the original microcontroller that I tried to simply program externally.</p> <p>any help is appreciated, thanks for reading!</p>
<p>In the case of using an Arduino as a USB/UART (FTDI) adapter to upload a sketch onto a barebones Arduino (ATMEGA328P) via its own bootloader, a reset of that MCU chip must preceed the sketch upload. That is because, immediately following the reset, the bootloader watches the serial traffic to see if this is marked as a sketch upload and, if so, processes it. If this reset operation fails, for example through a bad or missing connection, the sketch upload attempt will also fail. A good description of the sketch upload process can be found here: <a href="https://www.instructables.com/Overview-the-Arduino-sketch-uploading-process-and-/" rel="nofollow noreferrer">https://www.instructables.com/Overview-the-Arduino-sketch-uploading-process-and-/</a></p>
91173
|gps|mkr1010|
Connecting the MKR GPS shield by cable or as a shield
2022-10-29T11:28:24.877
<p>I have an MKR WiFi 1010 and an MKR GPS Shield. When I connect my GPS Shield using the I2C cable, it works fine.</p> <p>This works perfectly (the bottom is the MKR Motor Carrier):</p> <p><a href="https://i.stack.imgur.com/kcKGu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kcKGu.jpg" alt="enter image description here" /></a></p> <p>However, when I use it as a shield (hat?) using the pins, it doesn't.</p> <p>This doesn't work. The code blocks somewhere (I suspect <code>GPS.available()</code>):</p> <p><a href="https://i.stack.imgur.com/S5wPC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S5wPC.jpg" alt="enter image description here" /></a></p> <p>My question, should it work the same whether it is cabled or put on with the pins? Or should I change my code somehow?</p>
<p>From <a href="https://store.arduino.cc/collections/shields/products/arduino-mkr-gps-shield" rel="nofollow noreferrer">the shop page</a>:</p> <blockquote> <p>It interfaces with Arduino boards either through a serial interface, when used with headers and put on top of a MKR board, or through an I2C interface and a dedicated ESLOV cable supplied as bundle.</p> </blockquote> <p>From Arduino_MKRGPS library <a href="https://www.arduino.cc/reference/en/libraries/arduino_mkrgps/begin/" rel="nofollow noreferrer">reference</a>:</p> <p><code>begin()</code> Parameters:</p> <ul> <li>GPS_MODE_I2C to use the MKR GPS with the I2C cable (default setting),</li> <li>GPS_MODE_SHIELD if using the MKR GPS as a shield.</li> </ul>
91182
|arduino-uno|arduino-ide|
How to reduce codes numbers
2022-10-30T20:50:11.123
<p>I am new in Arduino projects, i made a digital counter that counts from 00 to 99. Here is my code below</p> <pre><code>void setup() { pinMode(0,OUTPUT); pinMode(1,OUTPUT); pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(4,OUTPUT); pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(7,OUTPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); } void loop() { /* segment starts from 00*/ digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(4,HIGH); digitalWrite(0,LOW); digitalWrite(3,LOW); /* segment will now be 10, the 0 will continue counting up to 1*/ digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(5,HIGH); digitalWrite(4,LOW); /* the segment will now be 20 */ digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(4,HIGH); digitalWrite(5,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(4,LOW); digitalWrite(6,HIGH); digitalWrite(5,LOW); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(4,HIGH); digitalWrite(6,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(5,HIGH); digitalWrite(4,LOW); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(4,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(4,LOW); digitalWrite(7,HIGH); digitalWrite(6,LOW); digitalWrite(5,LOW); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(4,HIGH); /* the segment will now be 9 0 */ digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(3,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(0,LOW); digitalWrite(1,HIGH); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(2,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(1,HIGH); digitalWrite(0,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(3,HIGH); digitalWrite(0,LOW); digitalWrite(1,LOW); digitalWrite(2,LOW); delay(500); digitalWrite(0,HIGH); delay(500); digitalWrite(4,LOW); digitalWrite(7,LOW); /* when it gets here the segment resets to 00*/ } </code></pre> <p><a href="https://i.stack.imgur.com/IsTFW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IsTFW.jpg" alt="arduino counter" /></a> It works pretty fine but the problem i have is the code is too long, is there a method i can use to reduce the length of the codes?</p>
<p>I suggest you look up how to do loops in a C or C++ programming tutorial. For example you can replace:</p> <pre><code>void setup() { pinMode(0,OUTPUT); pinMode(1,OUTPUT); pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(4,OUTPUT); pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(7,OUTPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); } </code></pre> <p>with:</p> <pre><code>void setup() { for (int i = 0; i &lt;= 9; i++) pinMode(i,OUTPUT); } </code></pre>
91187
|led|digital|digital-in|
Cannot read LED state
2022-10-31T13:11:04.697
<p>I am running into a problem on a very basic functionality.</p> <p>I want to read the state of an LED. I have confirmed that under the specified circumstances, the LED receives 1.9V.</p> <p>I try to read its state with this code:</p> <pre><code>#define LED_1 5 void setup() { pinMode(LED_1, INPUT); } void loop() { int led_state = 0; if ( digitalRead(LED_1) ) led_state = 1; Serial.println(&quot;LED State is: &quot;); Serial.println(led_state); } </code></pre> <p>However, most of the time, the <code>led_state</code> is <code>0</code>. Sometimes, it goes to <code>1</code>, but then quickly goes back to <code>0</code>.</p> <p>Is it because the voltage is low?</p> <p>EDIT: I am hooking power directly to one pin of the LED, and the other pin goes to GND (from the same DC power supply). Also, the power pin from the LED enters inside Arduino Digital Pin 5.</p>
<p>On my understanding, this is what you made <a href="https://i.stack.imgur.com/eJdC3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJdC3.jpg" alt="my understanding" /></a></p> <p>But i think you should do it this way</p> <p><a href="https://i.stack.imgur.com/QtDNP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QtDNP.jpg" alt="how i think" /></a></p> <p>Here is the code</p> <pre><code> int value; float input; int delaytime=500; void setup() { pinMode(value,INPUT); Serial.begin(9600); //serial bud rate } void loop() { value=analogRead(A2); input=(value*5.0)/1022.0; Serial.println(value); Serial.println(&quot;LED state is: &quot;); Serial.println(input); delay(delaytime); } </code></pre>
91196
|arduino-mega|gps|
How to find the correct navigation course by gps navigation with Arduino?
2022-11-01T15:39:51.920
<p>I have a problem for about days ago and here it is :</p> <p>I have an RC plane and wanna make it autonomous via GPS navigation by Arduino</p> <p>I have an Arduino Mage 2560 onboard connected to a GPS Ublox-Neo-M8N (GPS module) and there is the problem</p> <p>I want my RC-Plane to read it's position and go to waypoints</p> <p>The Coordinates of two waypoints are defined before on a matrix variable like this example :</p> <pre><code>a [1] [3] = { {38.884675, -116.671035, 245} }; b [1] [3] = { {38.725019, -116.580951, 1180} }; ( 1st is Latitude, 2nd is Longitude and 3rd is height) </code></pre> <p>So i want my Arduino to read it's current position from gps module's data and calculate the correct Azimuth (correct horizontal angle) and the correct pitch angle (vertical angle) to navigate my plane to the waypoints</p> <p>and remember, when it reaches to the waypoint &quot;a&quot; with a few error (miss distance = 4 meters), it should be able to ignore navigation to the waypoint of variable &quot;a&quot; and then, navigate to waypoint &quot;b&quot;</p> <p>I WAND THE EXACT COMMAND FROM ANY LIBRARY TO CALCULATE THOSE TWO ANGLE FOR NAVIGATION (azimuth direction angle and pitch angle to navigate RC-Plane from everywhere o the waypoints</p>
<p>The computation is not difficult. Since your drone is unlikely to travel for thousands of kilometers, you can assume the Earth is locally flat, and the latitude and longitude are an orthogonal coordinate system. First, compute the vector to the next waypoint in Cartesian coordinates (dx, dy, dz):</p> <pre class="lang-cpp prettyprint-override"><code>// Defined at global scope. const float radians_per_degree = M_PI / 180; const float degrees_per_radians = 180 / M_PI; const float meters_per_degree = 1e7 / 90; // For every reading of the GPS: float dx = (waypoint.longitude - current.longitude) * meters_per_degree * cos(current.latitude * radians_per_degree); float dy = (waypoint.latitude - current.latitude) * meters_per_degree; float dz = waypoint.height - current.height; </code></pre> <p>Then, from this vector you can get the required angles:</p> <pre class="lang-cpp prettyprint-override"><code>float azimuth = atan2(dx, dy) * degrees_per_radians; float pitch_angle = atan(dz/sqrt(dx*dx + dy*dy)) * degrees_per_radians; </code></pre> <p>Note that the approximation breaks down if the drone has to travel for a distance that is a significant fraction of the distance to the closest pole. Note also that the approximation errors are inconsequential if you periodically update your estimate of azimuth and pitch angle: the errors will be corrected along the way as the drone gets closer and closer to the waypoint.</p> <p><strong>Edit</strong>: timemage posted a very interesting comment, and I would want to further expand on the precision issue. The AVR floating point support is indeed limited to single precision. For latitudes and longitudes in the range shown in the question, the numerical resolution (formally, the <a href="https://en.wikipedia.org/wiki/Unit_in_the_last_place" rel="nofollow noreferrer">unit in the last place</a>) is (3.81×10<sup>−6</sup>)° for the latitude and (7.63×10<sup>−6</sup>)° for the longitude. This translates to about 42 cm and 66 cm respectively on the surface of the Earth. It may be just good enough to hit the waypoint to within 4 m.</p> <p>You could increase the resolution by storing the latitude and longitude in microdegrees, as 32-bit integers. This should be easy if the GPS always gives 6 digits after the decimal point: just ignore that decimal point. Then, once the quantities <code>waypoint.longitude - current.longitude</code> and <code>waypoint.latitude - current.latitude</code> are computed, you can safely use floating point for the rest of the computations.</p>
91240
|arduino-ide|sketch|
How to unload a sketch
2022-11-06T11:17:24.163
<p>I've loaded a sketch onto Arduino using the Ardunio IDE and it works but when I press the reset button I realize it doesn't remove the program. Is there a way to unload the program? Why? Because when I take it apart to put it away I don't know if having that program turning pins on or off and having nothing connected to it would break anything.</p>
<p>You can't remove a program by resetting the Arduino. If you want to be sure that it can't activate any pins in your next experiment, then just before you finish with it, upload a new program that does nothing, such as the Basics | Bare Minimum example program. It will effectively replace the previous program.</p> <p>At power-up, all of your pins[*] get configured as inputs during power-up. With the Bare Minimum program, nothing will change those pins, until you start writing &amp; uploading new code that modifies them.</p> <p>[*] Note that the bootloader will re-configure pin-1, the serial transmitter pin, as an output.</p>
91242
|library|compile|compilation-errors|arduino-cli|
Library not found when using the arduino-cli command (although working with the Arduino IDE)
2022-11-06T15:35:25.477
<p>I have a sketch which I can upload without problem with the Arduino IDE. I installed the arduino-cli Version: 0.28.0 Commit: 06fb1909 Date: 2022-10-18T15:53:04Z. I want to compile and upload a code on an arduino uno and use the command line</p> <pre><code>arduino-cli compile --fqbn arduino:avr:uno mysketch.ino </code></pre> <p>but get the following error:</p> <pre><code>/path/to/mysketch.ino:44:10: fatal error: LiquidCrystal.h: No such file or directory #include &lt;LiquidCrystal.h&gt; ^~~~~~~~~~~~~~~~~ compilation terminated. Used platform Version Path arduino:avr 1.8.5 /Users/user/Library/Arduino15/packages/arduino/hardware/avr/1.8.5 Error during build: exit status 1 </code></pre> <p>how could I proceed to debug?</p>
<p>The LiquidCrystal library is bundles with Arduino IDE 1 so it is not installed in your sketchbook folder's <code>libraries</code> folder so CLI can't find it.</p> <p>Install the library with Arduino CLI or simply copy it from Arduino IDE 1 installation folder into <code>libraries</code> folder of your sketchbook.</p>