I am new to Arduino and Matlab. Recently I am doing a project with Arduino and Matlab, and I found a strange thing when I try to send some data to Arduino from Matlab.
Here is my code
delete(instrfind({'Port'},{'COM3'}))
clear all
s = serial('COM3','BaudRate',9600);
% set(s,'BytesAvailableFcnCount',10);
set(s,'Terminator','CR');
fopen(s);
% sss=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): ');
sss=2 ;
fwrite(s,sss,'char');
ss = fscanf(s,'%s');
ss
fclose(s);
and i get this
and when I cancel the comment of the sss=input line, whatever I type in the data send successfully. like this:
I want know HOW can I send a data to my Arduino without any input action.
Here is the Arduino code
int incomingByte = 0;
int motor2= 2 ;
int motor3= 3 ;
int motor4= 4 ;
int motor5= 5 ;
int motor6= 6 ;
int motor7= 7 ;
int motor8= 8 ;
int motor9= 9 ;
int matlabSignal;
int motorDir= 30 ;
void setup() {
// put your setup code here, to run once:
pinMode(motor2,OUTPUT);
pinMode(motor3,OUTPUT);
pinMode(motor4,OUTPUT);
pinMode(motor5,OUTPUT);
pinMode(motor6,OUTPUT);
pinMode(motor7,OUTPUT);
pinMode(motor8,OUTPUT);
pinMode(motor9,OUTPUT);
//en pin
pinMode(motorDir,OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()>0){
incomingByte = Serial.read();
Serial.println(incomingByte,DEC);
matlabSignal = incomingByte;
}
/*
digitalWrite(motor2,HIGH);
digitalWrite(motor3,HIGH);
digitalWrite(motor4,HIGH);
*/
switch (matlabSignal){
case 1:
digitalWrite(motor9,HIGH);
break;
case 2:
digitalWrite(motor2,HIGH);
break;
case 3:
digitalWrite(motor3,HIGH);
break;
case 4:
digitalWrite(motor4,HIGH);
break;
case 5:
digitalWrite(motor5,HIGH);
break;
case 6:
digitalWrite(motor6,HIGH);
break;
case 7:
digitalWrite(motor7,HIGH);
break;
case 8:
digitalWrite(motor8,HIGH);
break;
}
}
Related
I'm trying to send a telephone number and a code (I'm using de code to read it in Arduino and know if this number is for one contact or other, because I'm gonna save different telephone numbers) vía ble from a Flutter app to a Arduino device (device: BLE 33). I'm using the ArduinoBLE library and the flutter_blue library.
For sending the number I need 6 bytes: for example for the number 112233445 one byte is for 11, second byte is for 22, third byte is for 33, 4º byte 44 and 5º byte is 5. And the code f.e. 4, is in another byte.
In Arduino, the function that I'm using to read is settingsCharacteristic.readValue(buffer, size_of_buffer). And in Flutter is characteristic.write(List).
I would like to send "04112233445" -> 4 is the code and the rest is the number.
The problem is that in Arduino I only receive 4 bytes.
Flutter code:
void sendTelephoneNumber(BluetoothCharacteristic characteristic) {
String exampleCode = "01";
characteristic
.write(utf8
.encode(exampleCode + myController.text));
}
(myController is the controller for a TextField where I write the number)
Arduino code:
void t5Callback()
{
BLEDevice central = BLE.central();
if (central && central.connected())
{
if (settingsCharacteristic.written())
{
byte buffer[6];
settingsCharacteristic.readValue(buffer, 6);
for (int i = 0; i < 6; i++)
{
Serial.println(buffer[i]);
}
int code = buffer[0];
unsigned long telephone = 0;
telephone = (buffer[1] + 512 << 32) | (buffer[2] << 24) | (buffer[3] << 16) | (buffer[4] << 8) | (buffer[5]);
Serial.printf("Code: %d\n", code);
Serial.printf("Telephone: %lu\n", telephone);
switch (code) {
case 7:
saveTelephone1(telephone);
break;
case 8:
saveTelephone2(message);
break;
default:
//todo
break;
}
}
}
yield();
}
Finally I tried using a event handler for the characteristic and now it works.
Before this I tried with apps like LightBlue and nRF Connect but I still receive not more than 4 bytes.
I don't know why with the event handler works...
I want to have my Zedboard return a numeric value using the Xilinx lwIP example as a base but no matter what I do I can't figure out what stores the data received or transmitted.
I have found the void type payload but I don't know what to do with it.
Snapshot of one instance of payload and a list of lwIP files
Below is the closest function to my goal:
err_t recv_callback(void *arg, struct tcp_pcb *tpcb,
struct pbuf *p, err_t err){
/* do not read the packet if we are not in ESTABLISHED state */
if (!p) {
tcp_close(tpcb);
tcp_recv(tpcb, NULL);
return ERR_OK;
}
/* indicate that the packet has been received */
tcp_recved(tpcb, p->len);
/* echo back the payload */
/* in this case, we assume that the payload is < TCP_SND_BUF */
if (tcp_sndbuf(tpcb) > p->len) {
err = tcp_write(tpcb, p->payload, p->len, 1);
//I need to change p->paylod but IDK where it is given a value.
} else
xil_printf("no space in tcp_sndbuf\n\r");
/* free the received pbuf */
pbuf_free(p);
return ERR_OK;
}
Any guidance is appreciated.
Thanks,
Turtlemii
-I cheated and just made sure that the function has access to Global_tpcb from echo.c
-tcp_write() reads in an address and displays each char it seems.
void Print_Code()
{
/* Prepare for TRANSMISSION */
char header[] = "\rSwitch: 1 2 3 4 5 6 7 8\n\r"; //header text
char data_t[] = " \n\r\r"; //area for storing the
data
unsigned char mask = 10000000; //mask to decode switches
swc_value = XGpio_DiscreteRead(&SWCInst, 1); //Save switch values
/* Write switch values to the LEDs for visual. */
XGpio_DiscreteWrite(&LEDInst, LED_CHANNEL, swc_value);
for (int i =0; i<=7; i++) //load data_t with switch values (0/1)
{
data_t[8+2*i] = '0' + ((swc_value & mask)/mask); //convert one bit to 0/1
mask = mask >> 1;//move to next bit
}
int len_header = *(&header + 1) - header; //find the length of the
header string
int len_data = *(&data_t + 1) - data_t; //find the length of the data string
tcp_write(Global_tpcb, &header, len_header, 1); //print the header
tcp_write(Global_tpcb, &data_t, len_data, 1); //print the data
}
I have three INA226 current sensors connected to eUSCI_B, P1.6 and P1.7, on an MSP430FR5739 microcontroller.
My I2C write addr code gives just one NACKIFG, and then forever hangs. On the scope the signals look nearly perfect square, no overshoot and the rise and fall time is 10-20x less than pulse with time of a clock. I use 2k2 Pullups. The wires are about 8cm all together on a PCB.
Previously I even did not manage to get any interrupt, by moving the "UCB0IE |= UCNACKIE | ..." code outside of the UCWRST area, I at least got this one.
#include "i2c.h"
#include "main.h"
#include "uart.h"
#include "ina226.h"
volatile unsigned int RXByte=0;
unsigned char TXData[] ={0, 0, 0, 0}; // Pointer to TX data
unsigned char TXByteCtr=0;
unsigned char TXByteCnt=0;
unsigned char RXByteCnt=0;
volatile unsigned int RXWord=0;
void init_i2c() {
P1SEL1 |= (BIT7 | BIT6);
P1SEL0 &= ~(BIT7 | BIT6);
uart_puts("I2C initialized\n\r");
}
void i2c_write_addr(unsigned int addr, unsigned char byte) {
UCB0CTL1 = UCSWRST; // Enable Module Reset
UCB0CTL0 |= UCMODE_3 | UCMST; // I2C, Master mode, ACLK 12MHz
UCB0CTL1 |= UCSSEL__ACLK;
UCB0BRW = 120;//200; //15; // 24MHz/240 = 100kHz Clock, 24MHz/60 = 400kHz
UCB0I2CSA = addr;
UCB0CTLW1 = UCASTP_2; // Automatic stop and interrupt, reduce deglich to 25 ns
UCB0CTLW0 |= UCTR; //Tranciever
UCB0TBCNT = 1;
UCB0CTL1 &= ~UCSWRST;
UCB0IE |= UCNACKIE | UCTXIE0 | UCRXIE | UCBCNTIE | UCNACKIE | UCSTTIE | UCSTPIE;
TXData[0] = byte;
TXByteCtr = 1; // Load TX byte counter
while (UCB0CTL1 & UCTXSTP); // Ensure stop condition got sent
UCB0CTL1 |= UCTR + UCTXSTT; // I2C TX, start condition
__bis_SR_register(GIE + CPUOFF); // Enter LPM0 w/ interrupts
uart_puts("i2c_write_addr 6\n\r");
}
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = USCI_B0_VECTOR
__interrupt void USCIB0_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_B0_VECTOR))) USCIB0_ISR (void)
#else
#error Compiler not supported!
#endif
{
LED1OUT |= LED1B;
switch(__even_in_range(UCB0IV,0x1E)) {
case 0x00: break; // Vector 0: No interrupts break;
case 0x02: break; // Vector 2: ALIFG break;
case 0x04: // Vector 4: NACKIFG break;
UCB0CTL1 |= UCTXSTT; // Resend I2C start condition
uart_puts("NACKIFG\n\r");
break;
case 0x06: break; // Vector 6: STTIFG break;
case 0x08: break; // Vector 8: STPIFG break;
case 0x0a: break; // Vector 10: RXIFG3 break;
case 0x0c: break; // Vector 14: TXIFG3 break;
case 0x0e: break; // Vector 16: RXIFG2 break;
case 0x10: break; // Vector 18: TXIFG2 break;
case 0x12: break; // Vector 20: RXIFG1 break;
case 0x14: break; // Vector 22: TXIFG1 break;
case 0x16: // Vector 24: RXIFG0 break;
RXByte = UCB0RXBUF; // Get RX data
RXWord = RXWord <<8;
RXWord |= RXByte;
uart_puts("RXIFG0\n\r");
break;
case 0x18: // Vector 26: TXIFG0 break;
if (TXByteCtr) // Check TX byte counter
{
TXByteCtr--;
UCB0TXBUF = TXData[TXByteCtr]; // Load TX buffer
}
else
{
//UCB0IFG &= ~UCTXIFG; // Clear USCI_B0 TX int flag
//UCB0CTLW0 |= UCTXSTP;
__bic_SR_register_on_exit(CPUOFF);// Exit LPM0
}
uart_puts("TXIFG0\n\r");
break;
case 0x1a: // Vector 28: BCNTIFG break;
uart_puts("BCNTIFG\n\r");
__bic_SR_register_on_exit(CPUOFF); // Exit LPM0
break;
case 0x1c: // Vector 30: clock low timeout break;
LED1OUT ^= LED1B;
__bic_SR_register_on_exit(CPUOFF); // Exit LPM0
uart_puts("CLKLOWTO\n\r");
break;
case 0x1e: break; // Vector 32: 9th bit break;
default: break;
}
}
And my stripped down main.c
void configure_clock()
{
FRCTL0 = FWPW | NACCESS_2 | NPRECHG_1; // Change the NACCESS_x value to add the right amount of waitstates
// Configure Clock System
CSCTL0_H = CSKEY >> 8; // Unlock CS registers
CSCTL1 = DCOFSEL_3 | DCORSEL; // Set DCO = 24MHz
CSCTL2 = SELA__DCOCLK | SELS__DCOCLK | SELM__DCOCLK;// Set ACLK=VLO SMCLK=DCO
CSCTL3 = DIVA__2 | DIVS__1 | DIVM__2; // Set all dividers (A=12MHz, S=24MHz, M=12MHz)
CSCTL0_H = 0; // Lock CS registers
}
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
configure_clock();
//Configure Debug UART
init_uart_115200();
// Disable the GPIO power-on default high-impedance mode to activate
// previously configured port settings
PM5CTL0 &= ~LOCKLPM5;
//Configure i2c
init_i2c();
_enable_interrupts();
i2c_write_addr(U3_ADDR, 0xFE); // Already stops here
uart_puts("INA216 ID: ");
uart_puti(i2c_read_uint(U3_ADDR));
while (1) {}
}
I have a sketch to take information (Lat, Long) from an EM-406a GPS receiver and write the information to an SD card on an Arduino shield.
The program is as follows:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <SD.h>
TinyGPSPlus gps;
SoftwareSerial ss(4, 3); //pins for the GPS
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;
void setup()
{
Serial.begin(115200); //for the serial output
ss.begin(4800); //start ss at 4800 baud
Serial.println("gpsLogger by Aaron McRuer");
Serial.println("based on code by Mikal Hart");
Serial.println();
//initialize the SD card
if(!card.init(SPI_FULL_SPEED, 9))
{
Serial.println("card.init failed");
}
//initialize a FAT volume
if(!volume.init(&card)){
Serial.println("volume.init failed");
}
//open the root directory
if(!root.openRoot(&volume)){
Serial.println("openRoot failed");
}
//create new file
char name[] = "WRITE00.TXT";
for (uint8_t i = 0; i < 100; i++){
name[5] = i/10 + '0';
name[6] = i%10 + '0';
if(file.open(&root, name, O_CREAT | O_EXCL | O_WRITE)){
break;
}
}
if(!file.isOpen())
{
Serial.println("file.create");
}
file.print("Ready...\n");
}
void loop()
{
bool newData = false;
//For one second we parse GPS data and report some key values
for (unsigned long start = millis(); millis() - start < 1000;)
{
while (ss.available())
{
char c = ss.read();
//Serial.write(c); //uncomment this line if you want to see the GPS data flowing
if(gps.encode(c)) //did a new valid sentence come in?
newData = true;
}
}
if(newData)
{
file.write(gps.location.lat());
file.write("\n");
file.write(gps.location.lng());
file.write("\n");
}
file.close();
}
When I open up the file on the SD card when the program is finished executing, I get a message that it has an encoding error.
I'm currently inside (and unable to get a GPS signal, thus the 0), but the encoding problem needs to be tackled, and there should be as many lines as there are seconds that the device has been on. There's only that one. What do I need to do to make things work correctly here?
Closing the file in the loop, and never reopening it, is the reason there's only one set of data in your file.
Are you sure gps.location.lat() and gps.location.lng() return strings, not an integer or float? That would explain the binary data and the "encoding error" you see.
Using Embarcadero C++ Builder 2010, I'm trying to detect specific web server devices connected to a network.
I'm interrogating those devices by calling a CGI function using TIdHTTP and analyzing the answer on a range of IP address.
I am using IdHTTP->ConnectTimeout and IdHTTP->ReadTimeout parameters to throws an exception if there's no connection by the time the timeout elapses. This should happen when TIdHTTP is interrogating an unexpected devices, in this case I release IdHTTP by calling IdHTTP->Free().
It works fine on Windows 7, but on Windows XP the timeout doesn't apply, so it can take up to 10 minutes before IdHTTP.get() stop.
By removing those two parameters the app work a bit faster on Windows XP but still take to long compare to the timeout than I am expecting.
I found this related subject without real solutions: Indy 10 + SSL = works in Windows 7, does not work on XP
This is a part of the source code:
#include "winsock2.h"
String url = "http://" + anIpAddress + "/myCGIFunction.cgi";
TMemoryStream *XML = new TMemoryStream;
AnsiString answer="";
p_IdHTTP = new TIdHTTP(NULL);
try
{
p_IdHTTP->ConnectTimeout = 2000;
p_IdHTTP->Get(url,XML);
XML->Position = 0;
answer=ReadStringFromStream(XML);
p_IdHTTP->Free();
}
catch (...)
{
p_IdHTTP->Free();
}
My questions are:
Why does IdHTTP->ConnectTimeout isn't working on Windows XP?
And do you have any idea to replace this parameter to release/destroyed the IdHTTP after a specific time?
Update:
void __fastcall Func::MyFunc()
{
AnsiString anIpAddress= "20.20.20.11";
String url = "http://" + anIpAddress + "/myCGIFunction.cgi";
TMemoryStream *XML = new TMemoryStream;
AnsiString answer="";
p_IdHTTP = new TIdHTTP(NULL);
try
{
p_SSLHandler=new TIdSSLIOHandlerSocketOpenSSL(p_IdHTTP);
p_SSLHandler->SSLOptions->Method= sslvSSLv23;
p_IdHTTP->ConnectTimeout = 2000;
p_IdHTTP->ReadTimeout=400;
p_IdHTTP->IOHandler=p_SSLHandler;
p_IdHTTP->OnConnected= IdHTTPConnected;
p_IdHTTP->OnStatus= IdHTTPStatus;
p_IdHTTP->Get(url,XML);
XML->Position = 0;
answer=ReadStringFromStream(XML);
p_IdHTTP->Free();
}
catch (...)
{
p_IdHTTP->Free();
}
}
void __fastcall Func::IdHTTPStatus(TObject *Sender, TIdStatus const AStatus, String const AStatusText){
String msgtest = ipAddress ;
switch (AStatus){
case (hsResolving):
msgtest+= " resolving...";
break;
case (hsConnecting):
msgtest+= " connecting...";
break;
case (hsConnected):
msgtest+= " connected...";
break;
case (hsDisconnecting):
msgtest+= " disconnecting...";
break;
case (hsDisconnected):
msgtest+= " disconnected...";
break;
case (hsStatusText):
msgtest+= " hsStatusText: " + AStatusText;
break;
default:
msgtest+= " Other status ";
break;
}
aListBox->Items->Add(msgtest);
Application->ProcessMessages();
}
void __fastcall Func::IdHTTPConnected(TObject *Sender){
struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
setsockopt((unsigned int) p_IdHTTP->Socket->Binding, SOL_SOCKET,
SO_RCVTIMEO, (char *)&timeout, sizeof(timeout) );
setsockopt ((unsigned int) p_IdHTTP->Socket->Binding, SOL_SOCKET, SO_SNDTIMEO,
(char *)&timeout, sizeof(timeout));
}